28 lines
739 B
Markdown
28 lines
739 B
Markdown
|
# 翻转字符串里的单词
|
|||
|
|
|||
|
[Leetcode](https://leetcode.com/problems/reverse-words-in-a-string/)
|
|||
|
|
|||
|
1. 去除单词中的额外空格
|
|||
|
2. 翻转整个字符串
|
|||
|
3. 挨个翻转单词
|
|||
|
|
|||
|
双指针去除额外空格:
|
|||
|
|
|||
|
如果快指针指向的是空格则跳过;
|
|||
|
|
|||
|
如果快指针指向的不是空格则把 `s[fast]` 覆盖到 `s[slow]`;
|
|||
|
|
|||
|
如果快指针指向的是空格并且下一个指向的不是空格,则在 `s[slow]` 处添加一个新空格(前提是 `slow` 不为 `0`,因为这种情况代表字符串的开头是空格)。
|
|||
|
|
|||
|
翻转字符串:
|
|||
|
|
|||
|
```cpp
|
|||
|
void reverseSubStr(string &s, int begin, int end) {
|
|||
|
for (; begin < end; ++begin, --end) {
|
|||
|
auto tmp = s[begin];
|
|||
|
s[begin] = s[end];
|
|||
|
s[end] = tmp;
|
|||
|
}
|
|||
|
}
|
|||
|
```
|