题目
Given an input string, reverse the string word by word.
Example:
Input: "the sky is blue",
Output: "blue is sky the".
Note:
- A word is defined as a sequence of non-space characters.
- Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
- You need to reduce multiple spaces between two words to a single space in the reversed string.
题目要求我们对字符串中的单词颠倒次序,需要注意的是需要去掉字符串前后的空白字符,单词与单词之间出现多个空白字符时,也需要去掉多的空白字符,只剩下一个,也就是说我们需要注意以下情况:
- 字符串只有空白字符 " " >> 更改后的字符串为空字符串。
- 字符串前后有空白字符如:" the sky is blue " >> 更改后的字符串为 "blue is sky the"。
- 字符串单词之间有多个空白字符如:"the sky is blue"。 >> 更改后的字符串为"blue is sky the"。
我们首先除去字符串前后的空白字符,再从第一个非空字符开始读取字符串,一旦读到空白字符便可以存下该单词(只要单词不为空字符串),然后将存储单词的变量清空,进行下一个单词的读取,如果有多个空白字符,之前存储单词是变量会是空字符串,则跳过该空白字符,直至下一非空字符串开始读取,如此反复读取存储后反向输出即可。
C++代码如下:
class Solution {
public:
void reverseWords(string &s) {
string temp, result;
int i = 0, j = s.length() - 1;
//除去前后的空白字符串
while (i < s.length()) {
if (s[i] == ' ')
++i;
else
break;
}
while (j >= 0) {
if (s[j] == ' ')
--j;
else
break;
}
for ( ; i <= j; ++i) {
if (s[i] != ' ') {
temp += s[i];
}
//解决出现多个空白字符的情况
else if (temp != ""){
result = " " + temp + result;
temp = "";
}
}
if (temp != "") {
result = temp + result;
}
s = result;
}
};