题目描述:
给定一个字符串,逐个翻转字符串中的每个单词。
示例 1:
输入: "the sky is blue"
输出: "blue is sky the"
示例 2:
输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
说明:
- 无空格字符构成一个单词。
- 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
- 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
解题思路1:
利用内置 split 方法和 reverse 方法,由于字符之间可能有多余的空格,因此不要以空格进行分割。
Python之字符串转列表(split),列表转字符串(join)
代码1:
class Solution(object):
def reverseWords(self, s):
return " ".join(reversed(s.split())) # 或者这样的写法 return " ".join(s.split()[::-1])
解题思路2:
首先将s按照空格split划分转换为列表,然后对列表中的每个元素strip掉左右空格,再将这个列表反转,最后用单个空格将列表进行拼接
代码2:
class Solution(object):
def reverseWords(self, s):
return " ".join(item.strip() for item in s.split()[::-1])
解题思路3:
首先将s中元素的左右空格strip掉,再按照空格split划分转换为列表,再将这个列表反转,最后用单个空格将列表进行拼接
代码3:
class Solution(object):
def reverseWords(self, s):
return " ".join(s.strip().split()[::-1])
解题思路4: 先反转字符串再反转每个单词
来源于:leetcode
首先得把字符串转化成其他可变的数据结构,同时还需要在转化的过程中去除空格。
代码4:
class Solution:
def trim_spaces(self, s: str) -> list:
left, right = 0, len(s) - 1
# remove leading spaces
while left <= right and s[left] == ' ':
left += 1
# remove trailing spaces
while left <= right and s[right] == ' ':
right -= 1
# reduce multiple spaces to single one
output = []
while left <= right:
if s[left] != ' ':
output.append(s[left])
elif output[-1] != ' ':
output.append(s[left])
left += 1
print(output) # ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']
return output
def reverse(self, List, left, right):
while left < right:
List[left], List[right] = List[right], List[left]
left, right = left + 1, right - 1
def reverse_each_word(self, List):
n = len(List)
start = end = 0
while start < n:
# go to the end of the word
while end < n and List[end] != ' ':
end += 1
# reverse the word
self.reverse(List, start, end - 1)
# move to the next word
start = end + 1
end += 1
def reverseWords(self, s):
# converst string to char array
# and trim spaces at the same time
l = self.trim_spaces(s)
# reverse the whole string
self.reverse(l, 0, len(l) - 1)
# reverse each word
self.reverse_each_word(l)
return ''.join(l)
s = Solution()
str = " hello world! "
print(s.reverseWords(str))
题目来源:
https://leetcode-cn.com/problems/reverse-words-in-a-string/