给定一个字符串,逐个翻转字符串中的每个单词。
示例 1:
输入: "the sky is blue"
输出: "blue is sky the"
示例 2:
输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
说明:
无空格字符构成一个单词。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
思路:
拿一个栈存放string,遇到空格或者最后一项就放入栈中,入栈时如果栈空时候存在空格,则不放入,排除开头的空格。入栈时如果栈顶是空格,当前元素也是空格,则不放入,排除中间重复的空格。出栈时如果res为空但栈顶为空格,则不加入res,排除尾巴的空格,具体实现如下。
class Solution {
public:
string reverseWords(string s) {
stack<string> st;
string res;
string temp;
for(int i=0;i<s.size();i++)
{
if(s[i]==' ')
{
if(!temp.empty())
{
st.push(temp);
temp.clear();
}
if(!st.empty() && st.top()!=" ")
{
st.push(" ");
}
}
else
{
temp.push_back(s[i]);
if(i==s.size()-1)
{
st.push(temp);
}
}
}
while(!st.empty())
{
temp=st.top();
st.pop();
if(temp==" " && res.empty())
{
continue;
}
res+=temp;
}
return res;
}
};
网友评论