reverse words in a string III
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: “Let’s take LeetCode contest”
Output: "s’teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
思路:第一想法是用栈,顺序扫描字符串,挨个入栈,当遇到空格时,就出栈至栈空,然后继续扫描字符串。扫描结束后,栈里还有一组单词,记得弹出到res里。
class Solution {
public:
string reverseWords(string s) {
//res最终返回的字符串
string res = "";
//引入栈
//策略:顺序对字符串的每个字母入栈
//如果遇到空格,出栈到res至栈空
stack <char> st;
for(int i =0;s[i] != '\0' ;i++)
{
if(s[i] != ' ')
{
st.push(s[i]);
}
else
{
while(!st.empty())
{
res+=(st.top());
st.pop();
}
res+=(" ");
}
}
//s扫描完了之后,栈里还有最后一个单词
while(!st.empty())
{
res += st.top();
st.pop();
}
return res;
}
};