344. 反转字符串【简单】

双指针秒了!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
void reverseString(vector<char>& s) {
int leftIndex = 0;
int rightIndex = s.size() - 1;

while (leftIndex < rightIndex) {
// 交换字符
char tmp = s[leftIndex];
s[leftIndex] = s[rightIndex];
s[rightIndex] = tmp;

// 移动指针
leftIndex++;
rightIndex--;
}
}
};

直接用自带的 reverse 函数……

1
2
3
4
5
6
7
class Solution {
public:
void reverseString(std::vector<char>& s) {
std::reverse(s.begin(), s.end());
}
};


© 2024 Montee | Powered by Hexo | Theme stellar


Static Badge