task for today:
1. 151.翻转字符串里的单词
2. 卡码网:55.右旋转字符串
------------------KMP算法:pending to be added -------------------
3. [optional] - place holder 459.重复的子字符串
4. [optional] - place holder 28. 实现 strStr()
----------------------------------------------------------------------------------
1. 151.翻转字符串里的单词
one thing need to be noted is that, when the s is splitted by the ' ' (space), the elements in s is either a word or ''(nothing), so the if condition within for loop should be ''(nothing) not ' '(space).
class Solution:
def reverseWords(self, s: str) -> str:
s = s.split(' ')
s = s[::-1]
new = []
for i in s:
if i != '':
new.append(i)
new = ' '.join(new)
return new
if the split function is not allowed to use, here is the result:
class solution:
def function(self, s:str):
s = list(s.strip())
i = 1
while i < len(s):
if s[i] == ' ' and s[i] == s[i-1]:
s.pop(i)
else:
i += 1
# print(s)
left, right = 0, len(s)-1
while left < right:
temp = s[left]
s[left] = s[right]
s[right] = temp
left += 1
right -= 1
# print(s)
left = 0
for i in range(len(s)):
if s[i] == ' ':
# print(left, i, True, s[:left], s[i-1::-1][:(i-left)], s[i:])
s = s[:left] + s[i-1::-1][:(i-left)] + s[i:]
# print(s)
left = i+1
s = s[:left] + s[i::-1][:(i-left+1)]
return ''.join(s)
besides, if a string is A = 'aaa bbbb aaac ', using A.split() can directly derive ["aaa", "bbbb", "aaac"]
2. 卡码网:55.右旋转字符串
In this practice, if the language is not java or python, try to avoid using additional space to make it more meaningful
The idea is, first do reverse for the entire string, then reverse the first k and then reverse the last string.
def function(k:int, s:str):
return s[len(s)-k:] + s[:len(s)-k]
KMP algorithm undertanding
[pending]