翻转字符串里的单词—leetcode151
生活随笔
收集整理的這篇文章主要介紹了
翻转字符串里的单词—leetcode151
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個字符串,逐個翻轉字符串中的每個單詞。
說明:
無空格字符構成一個 單詞 。
輸入字符串可以在前面或者后面包含多余的空格,但是反轉后的字符不能包括。
如果兩個單詞間有多余的空格,將反轉后單詞間的空格減少到只含一個。
?
示例 1:
輸入:"the sky is blue"
輸出:"blue is sky the"
示例 2:
輸入:" ?hello world! ?"
輸出:"world! hello"
解釋:輸入字符串可以在前面或者后面包含多余的空格,但是反轉后的字符不能包括。
示例 3:
輸入:"a good ??example"
輸出:"example good a"
解釋:如果兩個單詞間有多余的空格,將反轉后單詞間的空格減少到只含一個。
示例 4:
輸入:s = " ?Bob ? ?Loves ?Alice ? "
輸出:"Alice Loves Bob"
示例 5:
輸入:s = "Alice does not even like bob"
輸出:"bob like even not does Alice"
提示:
1 <= s.length <= 104
s 包含英文大小寫字母、數字和空格 ' '
s 中 至少存在一個 單詞
?
思路:遍歷一遍字符串,將詞存到stack里面,再吐出來保存?
class Solution { public:string reverseWords(string s) {string result = "", temp = "";stack<string> res;int n = s.length();for(int i=0;i<n;++i){if(s[i]==' '){if(temp!=""){res.push(temp);temp = "";}}else{temp += s[i];}}if(res.empty())return temp;if(temp!="")result += temp + ' ';int num = res.size();for(int i=0;i<num-1;++i){result += res.top()+' ';res.pop();}result += res.top();return result;} };?
總結
以上是生活随笔為你收集整理的翻转字符串里的单词—leetcode151的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 路径总和 II—leetcode113
- 下一篇: android cpu绑核