Leetcode-151.Reverse Words in a String
2015-12-30 03:42
246 查看
Problem Description:
Given an input string, reverse the string word by word.
For example,
Given s = ” the sky is blue “,
return “blue is sky the”.
Analysis:
This is probably by far the most common string manipulation interview question.
The idea to solve the problem is : First delete all the extra spaces, then reverse all the characters in the string, then reverse the letters of each word. For trim job, we need to pointers.
O(1) space solution :
Other short code :
O(N) both space and time complexity
Python code
Given an input string, reverse the string word by word.
For example,
Given s = ” the sky is blue “,
return “blue is sky the”.
Analysis:
This is probably by far the most common string manipulation interview question.
The idea to solve the problem is : First delete all the extra spaces, then reverse all the characters in the string, then reverse the letters of each word. For trim job, we need to pointers.
O(1) space solution :
class Solution { public: void reverseWords(string& s) { trim(s);//remove the whitespace and reverse. int l = 0; for (int i = 0; i < s.size(); ++i) { if (s[i] == ' ') { reverse(s.begin() + l, s.begin() + i); l = i + 1; } } reverse(s.begin() + l, s.end());// we need one more operation to reverse the last word. OR we could add a extra ' ' to the end, delete it when finish. return; } void trim (string& s) { int i; int n = s.size(); for (i = n - 1; i >= 0 && s[i] == ' '; --i){} s = s.substr(0, i + 1); reverse(begin(s), end(s)); for (i = s.size() - 1; i >= 0 && s[i] == ' '; --i){} s = s.substr(0, i + 1); n = s.size(); int tail = 0; for (i = 0; i < n;) { if (s[i] != ' ' || (s[i] == ' ' && s[i - 1] != ' ')) s[tail++] = s[i]; i++; } s = s.substr(0, tail);// remove the traling spaces or s.resize(tail); return ; } };
Other short code :
O(N) both space and time complexity
void reverseWords(string &s) { istringstream is(s); string tmp; is >> s; while(is >> tmp) s = tmp + " " + s; if(s[0] == ' ') s = ""; }
Python code
def reverseWords1(text): print " ".join(reversed(text.split())) print " ".join(text.split()[::-1])
相关文章推荐
- MAC 上安装MyEclipse2015
- 异步并发保持数据一致性
- scp: command not found如何解决
- Reverse Words in a String II
- 使用Python创建简单的HTTP和FTP服务
- 在VS的EF中连接MySQL
- [Javascript] Intro to Recursion - Detecting an Infinite Loop
- [leetcode] 136. Single Number 解题报告
- 个人认为老罗的思路非常好
- 【Unity3D游戏开发】性能优化之spine提高80~90%的效率 (三一)
- ubuntu怎么关防火墙
- Android ActionBar的基本用法
- NETTY 编码器介绍
- 大数据分析(一)探索性分析
- linux中网络工具nc|netcat的使用
- showAsAction属性详解
- 归档日志路径
- 顺序存储队列实现
- 队列顺序循环存储实现
- CSS强制性换行