生活随笔
收集整理的這篇文章主要介紹了
翻转字符串里面的单词(*****)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
思路
想一下,我們將整個字符串都反轉(zhuǎn)過來,那么單詞的順序指定是倒序了,只不過單詞本身也倒敘了,那么再把單詞反轉(zhuǎn)一下,單詞就正過來了。
所以解題思路如下:
1、移除多余空格
2、將整個字符串反轉(zhuǎn)
3、將每個單詞反轉(zhuǎn)
class Solution {
public:void reverse(string
& s
, int start
, int end
) {for (;start
< end
; start
++, end
--) {swap(s
[start
], s
[end
]);}}void removeExtraSpaces(string
&s
){int slowIndex
=0,fastIndex
=0;while(s
[fastIndex
]==' ') fastIndex
++;for(;fastIndex
<s
.size();fastIndex
++){if(fastIndex
-1>0&&s
[fastIndex
]==s
[fastIndex
-1]&&s
[fastIndex
]==' '){continue;}else s
[slowIndex
++]=s
[fastIndex
];}if(s
[slowIndex
-1]==' ') s
.resize(slowIndex
-1);else s
.resize(slowIndex
);}string
reverseWords(string s
) {removeExtraSpaces(s
);reverse(s
,0,s
.size()-1);int start
=0,end
=0;bool entry
=false; for(int ii
=0;ii
<s
.size();ii
++){if((!entry
)||s
[ii
- 1] == ' ')start
=ii
; entry
=true; }if(entry
&&s
[ii
]!=' '&&s
[ii
+1]==' '){end
=ii
;reverse(s
,start
,end
);entry
=false;}if(entry
&&(ii
==(s
.size()-1))){end
=ii
;reverse(s
,start
,end
);entry
=false;}}return s
;}
};
總結(jié)
以上是生活随笔為你收集整理的翻转字符串里面的单词(*****)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。