151. Reverse Words in a String

class Solution { public: void reverseWords(string &s) { if (s.empty()) return; string w; // detect words stack<string> words; for (char & c: s){ if (c != ' ') w.push_back(c); else { if (!w.empty()){ // we found a word! words.push(w); w = ""; // reset res } } } if (!w.empty()) words.push(w); string res; while(!words.empty()){ res += words.top(); res += ' '; words.pop(); } // remove the ending ' ' if (!res.empty()) res.pop_back(); s = res; } };
Thoughts:
- Use a pointer to detect words...
- Use an empty string to store single words
- Use a stack of string to store words in reverse order
- Finally pop the stack to form new string

Errors:
- memory error. Reason: when popping from a string, always check if it's empty!!!

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.