Reverse word in a string [leetcode]

来源:互联网 发布:xp 数据执行保护 编辑:程序博客网 时间:2024/06/07 00:54

/*
Reverse Words in a String Total Accepted: 35825 Total Submissions: 256704 My Submissions
Given an input string, reverse the string word by word.


For example,
Given s = "the sky is blue",
return "blue is sky the".


click to show clarification.


Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
*/

使用栈来存放中间的结果 

需要特别注意的是如果s = "   hello    wordld    "

对于字符串的 末尾 要特备注意处理 


class Solution{public:void reverseWords(string &s){stack <string> word_stack;string word = "";for(int i = 0;i < s.length();i ++){while(s[i] == ' '&& i < s.length()){i++;}while(s[i] != ' ' && i < s.length()){word += s[i];i++;}if(word != "")//避免字符串末尾出现空格的情况word_stack.push(word);word = "";}s = "";while(!word_stack.empty()){s += word_stack.top();word_stack.pop();if(!word_stack.empty())s += ' ';}}};


0 0