Loading...

10-01 leetcode 0557

链接 557. Reverse Words in a String III

题目

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

题解

暴力写,没啥好说的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def reverseWords(self, s: str) -> str:
results = []
temp = ""
result = ""
for i in range(len(s) - 1, -1, -1):
if s[i] != " ":
temp += s[i]
else:
result = temp + " " + result
temp = ""
result = temp + " " + result
return result.rstrip(" ")

不考虑重复遍历的话,一行流也行

1
2
3
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(word[::-1] for word in s.split())

Comment