151 Reverse Words in a String 翻轉字符串裏的單詞
阿新 • • 發佈:2018-04-06
rev index ++i .com CP blue 反轉字符串 程序員 -s
給定一個字符串,翻轉字符串中的每個單詞。
例如,
給定 s = "the sky is blue",
返回 "blue is sky the"。
對於C程序員:請嘗試用O(1) 時間復雜度的原地解法。
說明:
什麽構成一個詞?
一系列非空格字符組成一個詞。
輸入字符串是否可以包含前導或尾隨空格?
是。但是,您的反轉字符串不應包含前導或尾隨空格。
兩個單詞之間多空格怎麽樣?
將它們縮小到反轉字符串中的單個空格。
詳見:https://leetcode.com/problems/reverse-words-in-a-string/description/
class Solution { public: void reverseWords(string &s) { int size=s.size(); if(size==0||s.empty()) { return; } reverse(s.begin(),s.end()); int index=0; for(int i=0;i<size;++i) { if(s[i]!=‘ ‘) { if(index!=0) { s[index++]=‘ ‘; } int j=i; while(j<size&&s[j]!=‘ ‘) { s[index++]=s[j++]; } reverse(s.begin()+index-(j-i),s.begin()+index); i=j; } } s.resize(index); } };
151 Reverse Words in a String 翻轉字符串裏的單詞