Reverse Words in a String
2014-03-24 16:14
190 查看
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
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.
些麻烦了,懒得改。对于空格,只要while就能解决。
注意,string 和 char *是不一样的。
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.
些麻烦了,懒得改。对于空格,只要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'; } };
相关文章推荐
- 进程状态转换(了解)
- 游戏资源打包(2)
- Android - SimpleDateFormat 详解
- Android - SimpleDateFormat 详解
- 卡尔曼滤波原理
- Avoid strong reference cycles
- android自带的api的例子很多
- 央行称“会为互联网金融创新保留空间” 你信么?
- STL_map_multimap
- hive:(group by, having;order by)的使用;group by+多个字段,以及wiki说的group by两种使用限制验证
- Win7上UAC的限制无法使用文件拖拽解决方法
- hive:(group by, having;order by)的使用;group by+多个字段,以及wiki说的group by两种使用限制验证
- 设计模式------------策略模式
- 一口一口吃掉Struts(四)——几个知道就可以的属性 .
- <Lord don’t move that mountain>
- sleep()
- [暴力]uva10132 File Fragmentation
- 游戏资源打包(1)
- VS2010报 f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\occcont.cpp 中断错误
- linux常用C头文件