Reverse Words in a String
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
- 題目大意:給定一個字符串,對字符串進行逆轉。
- 解題思路:看到這道題目有兩種思路:
1)用兩個指針從前到后掃描,分開單詞,先對每個單詞進行逆轉,最后再對整個字符串逆轉;
比如題目中給的例子:先對每個單詞進行逆轉得到的結果:"eht yks si eulb",然后再整體逆轉即可得到"blue is sky the"。
2)根據空格切分字符串,將切分得到的單詞存到vector中,然后將vector中的單詞從末尾開始輸出即可。
在衡量了兩種方法之后,覺得第二種方法代碼更加簡潔方便,便選擇了第二種思路。
- 實現:
void reverseWords(string &s) { int i=0,j=0; int len = s.length(); vector<string> splitResult; while(i<len) { if(s[i]==' ') i++; else { j=i+1; while(j<=len) { if(s[j]==' '||j==len) { string tempStr = s.substr(i,j-i); splitResult.push_back(tempStr); i=j+1; break; } else j++; } } } int size = splitResult.size(); if(size>0) { s=""; for(i=size-1;i>0;i--) s+=splitResult[i]+" "; s+=splitResult[i]; } else { s=""; } }
注意的地方:我一開始提交就提示錯誤,要考慮到空字符串以及只有空格組成的字符串,因此要在最后作一個判斷,如果splitResult為空,則直接把s賦值為""即可。