公众号:爱写bug Write a function that reverses a string. The input string is given as an array of characters char[]
.python
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[]
的形式给出。this
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。spa
你能够假设数组中的全部字符都是 ASCII 码表中的可打印字符。指针
Example 1:code
Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"]
Example 2:ci
Input: ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"]
第一个字符与最后一个交换位置,继而第二个与倒数第二个交换位置,一直交换到到中位数 结束。字符串
Java:get
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:
总之,使用双指针技巧的典型场景之一是你想要
从两端向中间迭代数组。
这时你能够使用双指针技巧:
一个指针从始端开始,而另外一个指针从末端开始。