-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path151.反转字符串中的单词.py
113 lines (105 loc) · 2.9 KB
/
151.反转字符串中的单词.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#
# @lc app=leetcode.cn id=151 lang=python3
#
# [151] 反转字符串中的单词
#
# https://leetcode.cn/problems/reverse-words-in-a-string/description/
#
# algorithms
# Medium (50.80%)
# Likes: 649
# Dislikes: 0
# Total Accepted: 300.9K
# Total Submissions: 591.8K
# Testcase Example: '"the sky is blue"'
#
# 给你一个字符串 s ,请你反转字符串中 单词 的顺序。
#
# 单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。
#
# 返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。
#
# 注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。
#
#
#
# 示例 1:
#
#
# 输入:s = "the sky is blue"
# 输出:"blue is sky the"
#
#
# 示例 2:
#
#
# 输入:s = " hello world "
# 输出:"world hello"
# 解释:反转后的字符串中不能存在前导空格和尾随空格。
#
#
# 示例 3:
#
#
# 输入:s = "a good example"
# 输出:"example good a"
# 解释:如果两个单词间有多余的空格,反转后的字符串需要将单词间的空格减少到仅有一个。
#
#
#
#
# 提示:
#
#
# 1 <= s.length <= 10^4
# s 包含英文大小写字母、数字和空格 ' '
# s 中 至少存在一个 单词
#
#
#
#
#
#
#
# 进阶:如果字符串在你使用的编程语言中是一种可变数据类型,请尝试使用 O(1) 额外空间复杂度的 原地 解法。
#
#
# @lc code=start
class Solution:
def reverseWords(self, s: str) -> str:
# # 1. python O(N) O(N)
# return ' '.join(reversed(s.split()))
# 2. 自行编写函数 O(N) O(N)
def trim_spaces(s:str):
left, right = 0, len(s) - 1
while left <= right and s[left] == ' ':
left += 1
while left <= right and s[right] == ' ':
right -= 1
res = []
while left <= right:
if s[left] != ' ':
res.append(s[left])
elif res[-1] != ' ':
res.append(s[left])
left += 1
return res
def reverse(l:list, left, right):
while left < right:
l[left], l[right] = l[right], l[left]
left, right = left+1, right-1
def reverse_word(l:list):
start, right = 0, len(l) - 1
end = start
while start <= right:
while end <= right and l[end] != ' ':
end += 1
else:
reverse(l, start, end-1)
start = end + 1
end += 1
l = trim_spaces(s)
reverse(l, 0, len(l)-1)
reverse_word(l)
return ''.join(l)
# @lc code=end