内容简介:公众号:爱写bugWrite a function that reverses a string. The input string is given as an array of charactersDo not allocate extra space for another array, you must do this by
Leetcode 344:Reverse String 反转字符串
公众号:爱写bug
Write a function that reverses a string. The input string is given as an array of characters char[] .
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
不要给另外的数组分配额外的空间,你必须 原地修改输入数组 、使用 O(1) 的额外空间解决这一问题。
你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
Example 1:
Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"]
解题思路:
第一个字符与最后一个交换位置,继而第二个与倒数第二个交换位置,一直交换到到中位数 结束。
代码:
Java:
class Solution {
public void reverseString(char[] s) {
char temp;
for(int i=0,j=s.length-1;i<j;i++,j--){
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
Python3:
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
i = 0
j = len(s) - 1
while (i < j):
s[i], s[j] = s[j], s[i]#交换赋值
i+=1
j-=1
其实py3有很多好玩的操作,比如这道题可以这样: s=list(reversed(s)) 因为 reversed() 函数返回的是一个迭代器,所以要用 list() 函数才行。但是速度不快。
如果是字符串反转而不是数组还可以这样 s=s[::-1] (字符串切片: string[start:stop:step] )
总结:
这道题应当解释双指针问题最常引用的题目了,其思想是将第一个元素与末尾进行交换,再向前移动到下一个元素,并不断地交换,直到它到达中间位置。
我们可以同时使用两个指针来完成迭代:一个 从第一个元素开始 ,另一个 从最后一个元素开始 。持续交换它们所指向的元素,直到这两个指针相遇。
摘自Leetcode:
总之,使用双指针技巧的典型场景之一是你想要
从两端向中间迭代数组。
这时你可以使用双指针技巧:
一个指针从始端开始,而另一个指针从末端开始。
以上所述就是小编给大家介绍的《Leetcode 344:Reverse String 反转字符串(python、java)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 使用位运算、值交换等方式反转java字符串-共四种方法
- LeetCode 之 JavaScript 解答第344题 —— 反转字符串(Reverse String)
- LeetCode每日一题: 反转字符串中的元音字母(No.345)
- PHP细节:foreach、(汉子)字符串反转、isset,empty用法区别以及0、‘’、null之间关系
- LeetCode 之 JavaScript 解答第151题 —— 反转字符串中的单词 (Reverse Words in a String)
- Go数组反转练习
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Programming in Haskell
Graham Hutton / Cambridge University Press / 2007-1-18 / GBP 34.99
Haskell is one of the leading languages for teaching functional programming, enabling students to write simpler and cleaner code, and to learn how to structure and reason about programs. This introduc......一起来看看 《Programming in Haskell》 这本书的介绍吧!