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.
Follow up: For C programmers, try to solve it in-place in O(1) space.
Analysis
For an in-place O(1) space solution we can solve in three steps.
Trim extra spaces
Reverse whole string
reverse each word
However, this is takes longer. If we have string with m words of average length x and is n characters long, it would take O(n+m*x)? 🚧
classSolution { private: voidtrim(string& s, int i){ while (i < s.size()) { if (s[i] == ' ') s.erase(i, 1); elsebreak; } }
string::iterator rword(string &s, string::iterator start){ auto end = start; while (*end != ' ') { end++; } reverse(start, end); return end; }
public: voidreverseWords(string &s){ // trim leading spaces trim(s, 0);
// trim remaining extra spaces int i = 0; while (i < s.size()) { if (s[i] != ' ') { i++; } else { trim(s, i+1); }
}
//reverse the whole input reverse(s.begin(), s.end());
//reverse each word auto it = s.begin(); while (it != s.end()) { it = rword(s, it); it++; //skip spaces between words } } };
This one goes into an infinite loop.
Accepted (slow)
Used Visual Studio Debugger to step through and find the cycle. Looks like we need to be careful about moving iterators while maintaining single space between words. All in all this is a very complex solution.
classSolution { private: inttrim(string& s, int i){ while (i < (int) s.size()) { if (s[i] == ' ') s.erase(i, 1); elsebreak; } return i + 1; // skip to non-space char (may be past end of string) }
string::iterator rword(string &s, string::iterator start){ auto end = start; while (end != s.end() && *end != ' ') { end++; } reverse(start, end); return end; }
public: voidreverseWords(string &s){ // trim leading spaces trim(s, 0);
// trim remaining extra spaces int i = 0; while (i < (int) s.size()) { if (s[i] != ' ') { i++; } else { i = trim(s, i + 1); }
}
//reverse the whole input reverse(s.begin(), s.end());
// trim any spaces left over from last run trim(s, 0);
//reverse each word auto it = s.begin(); while (it != s.end()) { it = rword(s, it); if (it != s.end()) it++; //skip spaces between words } } };
intmain() { Solution sol; string str = " This is a test "; sol.reverseWords(str); cout << "Reversed: " << str << endl; return0; }
Accepted(improved) [TODO]
With C++ stringstream is an effective option for problems such as these.