mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
modified 151. Add 2 python versions. No need to implement Carlo's idea in such a complecated way by inviting extra space.
This commit is contained in:
@ -438,6 +438,38 @@ class Solution:
|
||||
|
||||
```
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
def reverseWords(self, s: str) -> str:
|
||||
# method 1 - Rude but work & efficient method.
|
||||
s_list = [i for i in s.split(" ") if len(i) > 0]
|
||||
return " ".join(s_list[::-1])
|
||||
|
||||
# method 2 - Carlo's idea
|
||||
def trim_head_tail_space(ss: str):
|
||||
p = 0
|
||||
while p < len(ss) and ss[p] == " ":
|
||||
p += 1
|
||||
return ss[p:]
|
||||
|
||||
# Trim the head and tail space
|
||||
s = trim_head_tail_space(s)
|
||||
s = trim_head_tail_space(s[::-1])[::-1]
|
||||
|
||||
pf, ps, s = 0, 0, s[::-1] # Reverse the string.
|
||||
while pf < len(s):
|
||||
if s[pf] == " ":
|
||||
# Will not excede. Because we have clean the tail space.
|
||||
if s[pf] == s[pf + 1]:
|
||||
s = s[:pf] + s[pf + 1:]
|
||||
continue
|
||||
else:
|
||||
s = s[:ps] + s[ps: pf][::-1] + s[pf:]
|
||||
ps, pf = pf + 1, pf + 2
|
||||
else:
|
||||
pf += 1
|
||||
return s[:ps] + s[ps:][::-1] # Must do the last step, because the last word is omit though the pointers are on the correct positions,
|
||||
```
|
||||
|
||||
Go:
|
||||
|
||||
|
Reference in New Issue
Block a user