leetcode 151 —— Reverse Words in a String
2015-08-18 16:18
393 查看
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
思路:
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
思路:
class Solution { public: void reverseWords(string &s) { int left = 0; while (left < s.size() && s[left] == ' ') { s.erase(left, 1); } int right = s.size() - 1; while (right >= 0 && s[right] == ' ') { s.erase(right, 1); right = s.size() - 1; } eraseMidEmp(s); int n = s.size(); for (int i = 0; i < n / 2; i++) { char tmp = s[i]; s[i] = s[n - 1 - i]; s[n - 1 - i] = tmp; } cout << s << endl; int j = 0; while (j < n) { int cnt = 0; while (j + cnt<n && s[j + cnt] != ' ') { cnt++; } if (cnt > 1) { reverseOneWord(s, j, j + cnt - 1); j += cnt; } else { j++; } } } void reverseOneWord(string &s, int start, int end) { int n = (end - start + 1) / 2; for (int i = 0; i < n; i++) { char tmp = s[start + i]; s[start + i] = s[end - i]; s[end - i] = tmp; } } void eraseMidEmp(string &s) { int i = 0; while (i + 1 < s.size()) { if (s[i] == ' '&&s[i + 1] == ' ') { s.erase(i, 1); } else i++; } } };
相关文章推荐
- Vmware Tools安装出错的解决方法
- JAVA 生成 UUID
- java实现排序算法之2-路插入排序,直接插入排序,折半插入排序
- linux shell中"2>&1"含义
- Android 用户反馈界面的实现
- Linux 设备驱动的移植
- C++对象模型——站在对象模型的尖端 (第七章)
- MySql配置优化
- 【appium】查看Android应用包名、Activity的几个方法
- HTML5 随手记(4)
- AJAX中不跨域和跨域问题的解决方法
- javascript +.net 构建restful API 应用
- 对比jQuery和AngularJS的不同思维模
- Android 代码混淆的实践
- 面向对象编程(2)
- 如何用MFC创建透明画板
- 从尾到头打印链表
- 中文乱码问题(转)charset pageEncoding等区别
- Mac下一些小工具安装报错Note
- 路人甲