LeetCode:Reverse words in a String
Problem:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
解法一:全局翻转 局部翻转
核心代码
void reverseWords(string &str) { if(str.size()==0) return; auto beg = str.begin(); auto end = str.end(); reverse(beg,end); for(auto space = beg; space != end; ) { space = std::find(beg,end,' '); reverse(beg,space); beg = space + 1; } }
别人家的代码
解法二:类似栈的思想 从后往前再翻转 每翻转一个则追加到结果字符串中
void reverseWords(string &s) { string rs; for (int i = s.length()-1; i >= 0; ) { while (i >= 0 && s[i] == ' ') i--; if (i < 0) break; if (!rs.empty()) rs.push_back(' '); string t; while (i >= 0 && s[i] != ' ') t.push_back(s[i--]); reverse(t.begin(), t.end()); rs.append(t); } s = rs; }