leetcode笔记--Reverse Words in a String
2016-02-24 18:29
323 查看
题目:难度(Medium)
Given an input string, reverse the string word by word.
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.
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.
Subscribe to see which companies asked this question
Tags:String
Similar Problems:(M) Reverse Words in a String II
分析:1.不含空白符的连续串组成一个单词
2.颠倒后的字符串两侧不要有空白符,即使原串有
3.单词之间如果有多个空格,只留下一个
代码实现:
Given an input string, reverse the string word by word.
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.
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.
Subscribe to see which companies asked this question
Tags:String
Similar Problems:(M) Reverse Words in a String II
分析:1.不含空白符的连续串组成一个单词
2.颠倒后的字符串两侧不要有空白符,即使原串有
3.单词之间如果有多个空格,只留下一个
代码实现:
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ tmp = s.split() #原地反转 tmp.reverse() return " ".join(tmp)上面利用了python的很多内建函数,感觉有种作弊的嫌疑,下面自己老老实实的实现了一下:
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ result = [] tmpStr = "" for ch in s: if ch != " ": tmpStr += ch else: if tmpStr != "": result.append(tmpStr) tmpStr = "" if tmpStr != "": result.append(tmpStr) #原地反转 result.reverse() return " ".join(result)
相关文章推荐
- swift之闭包循环引用问题及解决方式
- ios学习----------SDWebImage框架解析(3)
- 二、大数据生态圈尝鲜
- lintcode-easy-Flip Bits
- codeforces 622E. Ants in Leaves
- 多线程——Java中继承Thread类与实现Runnable接口的区别
- Android的一些设计思想(201603)
- Lombok 安装、入门 - 消除冗长的 java 代码
- ios 如何通过XIB 或者storyboard 创建headView 和footerView?
- 模型选择准则之AIC和BIC
- 一个python 服务器程序性能分析
- activity生命周期
- Spring Annotation方式读取注入properties属性值
- mysql 基本使用
- 【Mac上的问题】ValueError: unknown locale: UTF-8
- lintcode-easy-Flatten Binary Tree to Linked List
- AIDL
- 欢迎使用CSDN-markdown编辑器
- springmvc集成Quartz
- java事件处理机制(自定义事件)