344. Reverse String
Posted dmndxld
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了344. Reverse String相关的知识,希望对你有一定的参考价值。
Question:
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.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
My idea:Use two pointers.Judge the time to end function.
class Solution: def reverseString(self, s) : """ Do not return anything, modify s in-place instead. """ if(s==[]): return a=0 b=len(s)-1 if(b==0): return if(b==1): z=s[a] s[a]=s[b] s[b]=z return while(a!=b): z=s[a] s[a]=s[b] s[b]=z a=a+1 b=b-1 if(a==b-1): z=s[a] s[a]=s[b] s[b]=z return
执行用时 : 220 ms, 在Reverse String的Python3提交中击败了47.07% 的用户
内存消耗 : 17.4 MB, 在Reverse String的Python3提交中击败了89.43% 的用户
他这里要求不要返回值,只要求改变s,所以写个return就可以了,编译器里面还是要写return s的
还有就是if里面不能同时判断两种类型 比如
if(s==[]|len(s)==1)
这样不行,会报错
以上是关于344. Reverse String的主要内容,如果未能解决你的问题,请参考以下文章