标签:blog http io strong for ar art div
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return
"blue is sky the
".
1 st ( 20 tries)
class Solution { vector<string> vs; public: void reverseWords(string &s) { string tmp; if(s == "") return; int start = 0; while(s[start] == ‘ ‘) start++; int end = s.length() - 1; while(s[end] == ‘ ‘) end--; if(start > end) { s = ""; return; } for(int i = start;i <= end;i++) { if(s[i] == ‘ ‘) { vs.push_back(tmp); tmp.clear(); while(s[i+1] == ‘ ‘) { i++; } } else { tmp.push_back(s[i]); } } if(tmp == "") ; else vs.push_back(tmp); s = ""; for(int i = vs.size() - 1;i > 0;i--) { s += vs[i]; s += ‘ ‘; } s += vs[0]; } };
2 nd ( 4 tries)
class Solution { public: void reverseWords(string &s) { int start = 0; //skip beginning space while(start < s.length() && s[start] == ‘ ‘) start++; int send = s.length() - 1; //skip end space while(send >= 0 && s[send] == ‘ ‘) send--; //change string s if(start > send) { s = ""; return; } else s = s.substr(start,send-start+1); vector<string> words; //change mid space to one space int wordbegin = 0; for(int i = 0;i < s.length();i++) { if(s[i] == ‘ ‘) { words.push_back( s.substr(wordbegin,i-wordbegin) ); while(i < s.length() && s[i] == ‘ ‘) i++; wordbegin = i; } if(i == s.length() - 1) { words.push_back( s.substr(wordbegin,i-wordbegin+1) ); } } //combination s = ""; for(int i = words.size() - 1;i >= 0;i--) { if(i == 0) s += words[i]; else { s += words[i]; s += " "; } } } };
【Leetcode】Reverse Words in a String,布布扣,bubuko.com
【Leetcode】Reverse Words in a String
标签:blog http io strong for ar art div
原文地址:http://www.cnblogs.com/weixliu/p/3924360.html