[leetcode] Reverse Words in a String

来源:互联网 发布:java 加载资源文件 编辑:程序博客网 时间:2024/05/22 14:02

From : https://leetcode.com/problems/reverse-words-in-a-string/

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) {        stack<string> stc;string tstr="";s += ' ';int len = s.length();for(int i=0; i<len; i++) {if(i==0 && s[i]==' ') continue;if(s[i]==' ' && s[i-1]==' ') continue;if(s[i]==' ' && tstr!="") {stc.push(tstr);tstr = "";} else {tstr += s[i];}}s="";while(!stc.empty()) {s += stc.top();stc.pop();if(stc.empty()) {break;}s += " ";}    }};
Solution 2:

class Solution {public:    void reverseWords(string &s) {        string ts;int end = s.size()-1, start = end;while(end>=0) {while(end>=0 && s[end]==' ') end--;start = end;while(start>=0 && s[start]!=' ') start--;if(start!=0 && start<end && ts!="") ts.append(" ");if(start < end) ts.append(s.substr(start+1, end-start));end = start;}s = ts;    }};



0 0