151.反转字符串中的单词
题解:
可以考虑如下步骤:
-
整体反转使用reverse()函数。
例如
the sky is blue
->eulb si yks eht
-
局部反转。
例如
eulb
->blue
可以在传来的串上进行操作,使用三个指针idx,start,end。
start的作用标记原来串上的单词首(同时兼具遍历的作用),end用来标记单词后一个位置(为空),idx记录新单词的插入后的位置。
注:本操作在同一个串上进行操作
class Solution { public: string reverseWords(string s) { // 反转整个字符串 reverse(s.begin(), s.end()); int n = s.size(); int idx = 0; for (int start = 0; start < n; ++start) { //如果当前字符为空,直接略过,不为空才开始操作 if (s[start] != ' ') { // 填一个空白字符然后将idx移动到下一个单词的开头位置 if (idx != 0) s[idx++] = ' '; // 循环遍历至单词的末尾 int end = start; while (end < n && s[end] != ' ') s[idx++] = s[end++]; // 反转整个单词 reverse(s.begin() + idx - (end - start), s.begin() + idx); // 更新start,去找下一个单词 start = end; } } s.erase(s.begin() + idx, s.end()); return s; } };
可能有部分同学疑问:
reverse(s.begin() + idx - (end - start), s.begin() + idx);
这一步为什么是s.begin() + idx - (end - start)而不是s.begin()+start
原因:start遍历的是原字符串的位置,它开头可能有多个空字符,中间也可能有多个空字符如果直接加start则不满足题目的要求,而使用s.begin() + idx - (end - start)的意思为:
idx表示当前插入后的末位置,end-start为单词的长度,idx-单词长度为新串单词的首位置。这样才能正确翻转。
如果还不能很好的理解,可以使用
"the sky is blue"
" hello world "
作为输入,调试一下,就能清楚了。