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 *是不一样的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 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 阅读(131) 评论(0) 编辑 收藏 举报
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步