leetcode Reverse Words in a String
题目连接
https://leetcode.com/problems/reverse-words-in-a-string/
Reverse Words in a String
Description
Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue”,
return “blue is sky the”.
class Solution { public: void reverseWords(string &s) { n = s.length(); string x = ""; reverse(s.begin(), s.end()); while (!op.empty()) op.pop(); for (size_t i = 0; i < n;) { while (i < n && s[i] == ' ') i++; if (i == n) break; while (i < n && s[i] != ' ') { op.push(s[i++]); } while (!op.empty()) { x += op.top(); op.pop(); } x += ' '; } if (x.length()) x.pop_back(); s = x; } private: size_t n; stack<char> op; };
By: GadyPu 博客地址:http://www.cnblogs.com/GadyPu/ 转载请说明