LC 0151 [M] Reverse Words in a String
Code with Senpai edited this page Jun 3, 2022
·
1 revision
class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(s.split()[::-1])
class Solution(object):
def reverseWords(self, s):
arr = list(s)
self.reverse_string(arr, 0, len(arr)-1)
self.reverse_word(arr)
word = self.trim_sides(arr)
res = self.trim_space(word)
return ''.join(res)
def reverse_string(self, arr, l, r):
'''reverse a given string'''
while l < r:
arr[l], arr[r] = arr[r], arr[l]
l += 1 ; r -= 1
return arr
def reverse_word(self, arr):
'''reverse every words in a string'''
l, r = 0 , 0
while r < len(arr):
while r < len(arr) and not arr[r].isspace(): r += 1
self.reverse_string(arr, l, r-1)
r += 1; l = r
return arr
def trim_sides(self, arr):
'''str.strip() basically'''
if ''.join(arr).isspace(): return []
l , r = 0, len(arr) - 1
while l < r and arr[l].isspace(): l += 1
while l < r and arr[r].isspace(): r -= 1
return arr[l:r+1]
def trim_space(self, word):
'''remove duplicating space in a word'''
if not word: return []
res = [word[0]]
for i in range(1, len(word)):
if res[-1].isspace() and word[i].isspace(): continue
res.append(word[i])
return res
class Solution:
def reverseWords(self, s: str) -> str:
def rev(s, l, r):
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
return
def rev_words(s):
i = 0
while i < len(s):
while i < len(s) and s[i] == ' ':
i += 1
if i == len(s):
break
# s[i] starts a word, now find j that ends a word
j = i
while j+1 < len(s) and s[j+1] != ' ':
j += 1
# s[j] ends a word
rev(s, i, j)
i = j + 1
def trim(s):
i, j = 0, 0 # j to be checked, i holds index of next chr
for j in range(len(s)):
if s[j] != ' ':
if i > 0 and j > 0 and s[j-1] == ' ': # this is key, to determine if we need add a space or not.
s[i] = ' '
i += 1
s[i] = s[j]
i += 1
return s[:i]
sentence = list(s)
rev(sentence, 0, len(sentence)-1)
rev_words(sentence)
arr = trim(sentence)
return ''.join(arr)
footer