Reverse Words in a String
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
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.
些麻烦了,懒得改。对于空格,只要while就能解决。
注意,string 和 char *是不一样的。
class Solution { public: void reverseWords(string &s) { stack<string> sk; if(s.size()==0)return ; int i = 0; int b = 0,e = 0; if(s.size()==1) { if(s[0] == ' ') { s = ""; return; } else return; } for(i = 0 ; i < s.size()-1;i++) { if(s[i] == ' '&&s[i+1] != ' ') { b = i+1; } else if(s[i] != ' ' && s[i+1] == ' ') { e = i+1; string tp = s.substr(b,e-b); sk.push(tp); } } if(s[s.size()-1] != ' ') { string tp = s.substr(b,s.size()); // if(b != e) { sk.push(tp); } } if(sk.empty()) { s=""; return; } s = sk.top(); sk.pop(); while(!sk.empty()) { string tp = sk.top(); s = s + ' '+tp; sk.pop(); } //s = s+'\0'; } };
posted on 2014-03-24 16:14 pengyu2003 阅读(130) 评论(0) 编辑 收藏 举报