LeetCode-字符串-反转字符串中的单词 II
生活随笔
收集整理的這篇文章主要介紹了
LeetCode-字符串-反转字符串中的单词 II
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
557. 反轉字符串中的單詞 III
class Solution { public:string reverseWords(string s) {s+=' '; //為了讓最后一個單詞進入循環string tempstr,res;vector<string> vecstr;for(char c:s){if(c==' '){reverse(tempstr.begin(), tempstr.end());vecstr.push_back(tempstr);tempstr.clear();}else {tempstr+=c;}}for(int i=0;i<vecstr.size();i++){res+=vecstr[i];res+=' ';}res.pop_back(); //去除最后一個空格return res;} };優化
class Solution { public:string reverseWords(string s) {s+=' '; //為了讓最后一個單詞進入循環string tempstr,res;for(char c:s){if(c==' '){reverse(tempstr.begin(), tempstr.end());res+=tempstr;res+=' ';tempstr.clear();}else {tempstr+=c;}}res.pop_back(); //去除最后一個空格return res;} };總結
以上是生活随笔為你收集整理的LeetCode-字符串-反转字符串中的单词 II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode-字符串-58. 最后一
- 下一篇: LeetCode-剑指 Offer 53