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)

这样不行,会报错

上一篇:EditPlus配置Java语法自动补全功能[转]


下一篇:微信小程序—修改日期