problem
557. Reverse Words in a String III
solution1:字符流处理类istringstream.
class Solution { public: string reverseWords(string s) { string ans = "", t = ""; istringstream is(s);// while(is >> t) { reverse(t.begin(), t.end()); ans += t + " ";//err. } ans.pop_back(); return ans; } };
solution2:单词首尾指针。
class Solution { public: string reverseWords(string s) { int start = 0, end = 0; while(start<s.size() && end<s.size()) { while(end < s.size() && s[end]!=' ') end++; for(int i=start, j=end-1; i<j; i++, j--)// { swap(s[i], s[j]);// } start = ++end; //start = end + 1; //end++; } return s; } };
参考
1. Leetcode_easy_557. Reverse Words in a String III;
2. Grandyang;
完