您的位置:首页 > 其它

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.单词之间如果有多个空格,只留下一个

代码实现:

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: