本文共 650 字,大约阅读时间需要 2 分钟。
题目:
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) { int i = 0; int start = -1; stackst; string temp = "", result = ""; s = s + ' '; while (i < s.length()) { if (s[i] != ' ') { if (start == -1) start = i; } else { if (start != -1) { temp = s.substr(start, i - start); st.push(temp); start = -1; } } i++; } while (!st.empty()) { result = result + st.top() + " "; st.pop(); } s = result.substr(0, result.length() - 1); }};
转载地址:http://futsi.baihongyu.com/