【LeetCode每天一题】Reverse String
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"]
Example 2: Input: ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"]
反转字符串:
方法一:主要的思路就是通过两个指针,一个指到开头,一个指到尾。然后交换位置。最终可以得到反转之后的字符串。时间复杂度为O(n), 空间复杂度为0(1)。
1 class Solution(object): 2 def reverseString(self, s): 3 """ 4 :type s: List[str] 5 :rtype: None Do not return anything, modify s in-place instead. 6 """ 7 if len(s) < 2: 8 return s 9 start, end = 0, len(s)-1 10 while start < end: 11 s[start], s[end] = s[end], s[start] 12 start += 1 13 end -= 1
方法二:可以利用栈的特性,从头遍历到尾,依此将数据存进栈中,然后在将数据弹出组成一个新的字符串就是反正之后的字符串。时间复杂度为O(n), 空间复杂度为O(n)。(当然这道题要求原地改变,所以这是不符合思路的)
方法三: 因为是使用的是Python, 所以可以直接使用一种办法就是 s[ : :-1]这样会直接将字符串进行反转,但是利用内置的模型,这不是这道题需要考察的东西。