Reverse Words in a String
来源:互联网 发布:linux 用终端打开文件 编辑:程序博客网 时间:2024/06/05 15:49
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:
这题感觉不难啊,但是ac率好低,可能是空格的情况需要仔细考虑吧。- 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的尾部往头遍历,遇到空格就继续前进;不是空格,再设置一个指针往前走,直到空格。然后把这段字符串反转下就下。
void reverseWords(string &s){ int len = s.size(); int i=len-1,j; string result="",tmp=""; while(i >= 0) { if(s[i]!=' ') { tmp += s[i]; for(j=i-1; j>=0&&s[j]!=' '; j--) tmp += s[j]; reverse(tmp.begin(), tmp.end()); i=j; result += tmp + " "; tmp=""; } if(s[i]==' ') i--; } int newlen=result.size(); if(newlen==0) s=""; else { result.erase(newlen-1); s=result; }}
0 0
- Reverse words in a string.
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- ASP.NET——RequiredFieldValidator控件和ValidationSummary控件
- 1407251636-hd-阿牛的EOF牛肉串.cpp
- Android获取assets子目录注意事项
- 多态、虚函数和动态关联
- 修改JSONObject.fromObject数字为null时被转换为0
- Reverse Words in a String
- HDU 1846 Brave Game
- 对于存放数据库时带有html标签问题
- pkg-config for mac 安装
- 【Visual C++】游戏开发笔记之五——游戏画面绘图(二)绘制位图
- NetBeans 8.0创建Java Web时没有web.xml的解决方法
- hdu-1007-Quoit Design
- HDU 1518 Square 搜索
- Codeforces Round #258 (Div. 2) E . Devu and Flowers 母函数+公式