LeetCode | Reverse Words in a String(字串中的單詞序反轉)
阿新 • • 發佈:2019-01-01
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
題目解析:
題目中要刪除多餘的空格,有一種比較簡單的方法,先將s字串賦給一個臨時字串tmp,將頭尾空格略去,兩個字間的空格只複製一次。然後對tmp進行常規操作。這樣需要兩遍遍歷。
也可以臨時設一個結果字串,和一個臨時的字串。一點一點處理
class Solution { public: void reverseWords(string &s) { string tmp; for(int i = s.size()-1;i >= 0;i--){ while(i >= 0 && s[i] == ' ') i--; if(i<0) break; if(!tmp.empty()) tmp.push_back(' '); string word; while(i>=0 && s[i]!=' ') word.push_back(s[i--]); reverse(word.begin(),word.end()); tmp.append(word); } s = tmp; } };