翻转单词顺序列(reverse翻转)
翻转单词顺序列
http://www.nowcoder.com/questionTerminal/3194a4f4cf814f63919d0790578d51f3
- 用栈存储单词 时间空间复杂度都为O(n)
- reverse 翻转字符串空间复杂度为O(1);
class Solution { public: string ReverseSentence(string str) { stack<string> stack; string ans; for(int i = 0; i < str.size(); i++){ if(str[i] != ' ')ans+=str[i]; else {stack.push(ans); ans.clear();} } while(!stack.empty()){ ans = ans+" "+stack.top(); stack.pop(); } return ans; } }; class Solution { public: string ReverseSentence(string str) { reverse(str.begin(),str.end()); int f = 0; for(int i = 0; i < str.size(); i++){ if(str[i]==' '){ reverse(str.begin()+f,str.begin()+i); f = i+1; } } reverse(str.begin()+f, str.end()); return str; } };