您的位置:首页 > 其它

20170225-leetcode-151-Reverse Words in a String

2017-02-25 20:57 375 查看

1.Description

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.

https://leetcode.com/problems/reverse-words-in-a-string/?tab=Description

解读

输入一个字符串,字符串中包含一些单词,单词之间由空格隔开,空格可能不止一个,并且前后也有可能有空格

要求,将单词反序排列,前后的空格去掉,单词之前如果本来有多个空格输出结果要变成一个空格

2.Solution

class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
slist=s.split(' ')
str=''
for item in reversed(slist):
if item=='':continue
str+=item.strip()+' '
return str.strip()


思路

把数据按照空格隔开

反着遍历

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