151.翻转字符串里的单词
怎么反转单词顺序?list.reverse().碰到空格,把单词加入list中。
class Solution:
def reverseWords(self, s: str) -> str:
s1 = []
word = ''
s += ' '
for i in range(len(s)):
if s[i] == ' ':
if word != '':
s1.append(word)
word = ''
else:
continue
else:
word += s[i]
s1.reverse()
return " ".join(s1)
但是你说有库不调是什么意思?
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(s.split()[::-1])
卡码网:55.右旋转字符串
这道题考的是怎么不引入额外空间,但是python的string不能修改,没办法了,人生苦短我用Python
k = int(input())
s = str(input())
s2 = s[-k:]+s[:-k]
print(s2)
28. 实现 strStr()
KMP,写一次错一次。原理还是好理解的。
class Solution:
def getNext(self, next: list[int], s: str) -> None:
j = 0
next[0] = 0
for i in range(1, len(s)):
while j > 0 and s[i] != s[j]:
j = next[j - 1]
if s[i] == s[j]:
j += 1
next[i] = j
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
next = [0] * len(needle)
self.getNext(next, needle)
j = 0
for i in range(len(haystack)):
while j > 0 and haystack[i] != needle[j]:
j = next[j - 1]
if haystack[i] == needle[j]:
j += 1
if j == len(needle):
return i - len(needle) + 1
return -1
459.重复的子字符串
KMP的应用,算一下next数组就知道怎么回事了,如果是符合要求的字符串,next矩阵前几个为0,后面递增,所以len(s) - next[-1]
对应重复子字符串的长度。
class Solution:
def getNext(self, next: list, s: str) -> list:
next[0] = 0
j = 0
for i in range(1, len(s)):
while j > 0 and s[j] != s[i]:
j = next[j - 1]
if s[j] == s[i]:
j += 1
next[i] = j
def repeatedSubstringPattern(self, s: str) -> bool:
if len(s) == 0:
return False
next = [0] * len(s)
j = 0
self.getNext(next, s)
if next[-1] != 0 and (len(s)%(len(s) - next[-1]) == 0):
return True
return False
但是简单题有简单题的做法,把这个字符串s
拼接在一起s+s
,掐头去尾后(s+s)[1:-1]
,这个s
仍然是其中一部分
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
return s in (s+s)[1:-1]
顺便复习下双指针,最近一周笔试面试改小论文累死了。。。