Given an input string, reverse the string word by word.

For example,
Given s = “the sky is blue”,
return “blue is sky the”.

用了很偷懒的办法=。=,就是用两个pointer把string根据空格拆成string array,最后倒着输出就完了。。(好把我太懒了)

Solution:


class Solution {
public:
        void reverseWords(string &s) {
                vector<string> strs;
    		int prevPtr = 0, backPtr = 0;
		while (s[prevPtr] == ' ')
			++prevPtr;
		backPtr = prevPtr;

		while (backPtr < s.length())
		{
			while (backPtr < s.length() && s[backPtr] != ' ')
				++backPtr;
			strs.push_back(s.substr(prevPtr, backPtr - prevPtr));
			while (backPtr < s.length() && s[backPtr] == ' ') ++backPtr;
			prevPtr = backPtr;
		}
		s = "";
		for (int i = strs.size() - 1; i >= 0; --i)
		{
			if (i != 0)
				s += strs[i] + " ";
			else s += strs[i];
		}
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *