leetcode344. 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.

不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。

You may assume all the characters consist of printable ascii characters.

Example 1:

1
2
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

1
2
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

1
2
3
4
5
6
void (vector<char>& s) {
if (s.empty()) return;
int f = 0, l = s.size() - 1;
while (f<l)
swap(s[f++], s[l--]);
}

总结

  1. 这题很简单,O(1)space,用双指针,前后向中间遍历,交换位置即可。
  2. 入口处要进行鲁棒性检查。