Reverse Words in a String
This commit is contained in:
@@ -7,6 +7,7 @@
|
||||
# 字符串
|
||||
|
||||
- [替换空格](./substitute_spaces.md)
|
||||
- [翻转字符串里的单词](./reverse_words_in_a_string.md)
|
||||
|
||||
# 经典代码
|
||||
|
||||
|
27
notes/src/reverse_words_in_a_string.md
Normal file
27
notes/src/reverse_words_in_a_string.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# 翻转字符串里的单词
|
||||
|
||||
[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;
|
||||
}
|
||||
}
|
||||
```
|
Reference in New Issue
Block a user