题目描述
题目链接: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.
例子
例子 1
Input: [“h”,“e”,“l”,“l”,“o”] Output: [“o”,“l”,“l”,“e”,“h”]
例子 2
Input: [“H”,“a”,“n”,“n”,“a”,“h”] Output: [“h”,“a”,“n”,“n”,“a”,“H”]
解题思路
前后双指针,一个指针指向数组头,另一个指针指向数组尾部,分别往后/前遍历,依次交换字符即可,代码如下:
#include <vector>
class Solution {
public:
void reverseString(std::vector<char>& s) {
int front = 0, back = s.size() - 1;
while (front < back) {
std::swap(s[front], s[back]);
front++;
back--;
}
}
};
- 时间复杂度: O(n)
- 空间复杂度: O(1)