LeetCode 翻轉字符串裏的單詞
阿新 • • 發佈:2019-03-25
sta pop stack size code style The span tin
給定一個字符串,逐個翻轉字符串中的每個單詞。
示例 1:
輸入: "the sky is blue
"
輸出: "blue is sky the
"
示例 2:
輸入: " hello world! "
輸出: "world! hello"
解釋: 輸入字符串可以在前面或者後面包含多余的空格,但是反轉後的字符不能包括。
示例 3:
輸入: "a good example" 輸出: "example good a" 解釋: 如果兩個單詞間有多余的空格,將反轉後單詞間的空格減少到只含一個。
解法:按要求模擬,首先前面有" "的都要去了,然後開始就是單詞了,每碰到一個" "就是一個單詞,用棧存儲起來就可以了。然後輸出的時候從棧當中拿出來輸出即可。
class Solution {
public:
string reverseWords(string s) {
stack<string> str;
string s0 = "";
if(s.empty())
{
s = "";
return s;
}
for(int i=0;i<s.length();i++)
{
if(s[i]!=‘ ‘)
{
s0 +=s[i];
continue;
} //得到字符組成字符串。
else if(!s0.empty())
{
str.push(s0);
s0="";
}
}
if(!s0.empty())
{
str.push(s0);
s0="";
}
while(!str.empty())
{
s0 +=str.top();
str.pop();
s0+=" ";
}
if(s0.empty())
{
s = "";
return s;
}
s0.erase(s0.end()-1);
s = s0;
return s;
}
};
LeetCode 翻轉字符串裏的單詞