leetcode 344. 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"]

难度:简单题

题目大意:反转字符串

思路:双指针、递归

方法一:递归

C++代码:

class Solution {
public:
    void dfs(vector<char> &s, int l, int r) {
        if (l >= r)
            return;
        swap(s[l], s[r]);
        dfs(s, l + 1, r - 1);
    }
    void reverseString(vector<char>& s) {
        dfs(s, 0, s.size() - 1);
    }
};

时间复杂度:$O(n)$

空间复杂度:$O(n)$(递归栈)

python3代码:

 1 class Solution:
 2     def reverseString(self, s: List[str]) -> None:
 3         """
 4         Do not return anything, modify s in-place instead.
 5         """
 6         def helper(left, right):
 7             if (left >= right):
 8                 return
 9             s[left], s[right] = s[right], s[left]
10             helper(left + 1, right - 1)
11         helper(0, len(s) - 1)
12             

方法二:双指针

C++代码:

1 class Solution {
2 public:
3     void reverseString(vector<char>& s) {
4         for(int i = 0, j = s.size() - 1; i < j; ++i,--j) {
5             swap(s[i], s[j]); //辅助变量实现、异或运算实现
6         }
7     }
8 };

python3代码:

 1 class Solution:
 2     def reverseString(self, s: List[str]) -> None:
 3         """
 4         Do not return anything, modify s in-place instead.
 5         """
 6         # s.reverse()
 7         # for i in range(len(s) // 2):
 8         #     s[i], s[-1-i] = s[-1-i], s[i]
 9         i, j = 0, len(s) - 1
10         while i < j:
11             s[i], s[j] = s[j], s[i]
12             i, j = i + 1, j - 1
13             

 

posted @ 2020-06-05 11:15  琴影  阅读(249)  评论(0编辑  收藏  举报