题目如下:
927. Reverse Words in a String II
Given an input character array, reverse the array word by word. A word is defined as a sequence of non-space characters.
The input character array does not contain leading or trailing spaces and the words are always separated by a single space.
Example
Given s = “the sky is blue”,
after reversing : “blue is sky the”
Challenge
Could you do it in-place without allocating extra space?
这题主要考string.find()的用法。
注意string.find(’ ', endPos+1)里面的endPos+1可以表示从什么地方开始找。
class Solution {
public:
/**
* @param str: a string
* @return: return a string
*/
string reverseWords(string &str) {
string result;
int startPos = -1, endPos = 0;
size_t len = str.size();
while (endPos < len) {
endPos = str.find(' ', endPos + 1);
if (startPos >= 0)
result = str.substr(startPos + 1, endPos - startPos - 1) + ' ' + result;
else
result = str.substr(startPos + 1, endPos);
startPos = endPos;
}
return result;
}
};