翻轉字串(坑比較多)
阿新 • • 發佈:2020-09-06
Given an input string, reverse the string word by word.
Example 1:
Input: "the sky is blue
" Output:"blue is sky the
"
Example 2:
Input: " hello world! " Output:"world! hello" Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: "a good example" Output:"example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
class Solution { public: //去掉多餘的空格 string reverseWords(string s) { int i=0; while(s[i] == ' ') s.erase(s.begin()); reverse(s.begin(),s.end()); i=0; while(s[i] == ' ') s.erase(s.begin()); //翻轉 int j=0; cout<<s<<endl; for(i=0;i<s.size();i++){ if(s[i] == ' '){ reverse(s.begin()+j,s.begin()+i); i++; while(s[i] == ' ') s.erase(s.begin()+i); j = i; } } //最後一個 reverse(s.begin()+j,s.end()); return s; }