案例三
旋转词练习
最优时间复杂度为O(N)
1、判断str1与str2长度是否相等,不等返回false
2、长度相等,生成str1+str1的大字符串
3、用KMP算法判断大字符串是否包含str2
Python中判断字符串是否在另外一字符串中可用
if B in C:
Python
class Solution():
def rotate(self,A,B):
if len(A)== len(B):
return False
else:
C = A + A
if B in C:
return True
else:
return False
案例四
句子的逆序练习题
解题思路:
1、准备逆序函数
Python中 列表的逆序函数 list.reverse() 字符串的逆序函数str[::-1]
2、每个单词逆序,整体再逆序 或整体先逆序,再每个单词逆序
或把每个单词提出来作为新列表的一个元素,把新列表逆序(不知道单词数,只能适用于Python列表)
class Solution():
def reverseSentence(self,A):
listA = list(A)
listA.append(' ')
strA = ''
listB = []
for i in range(len(listA)):
if listA[i] != ' ':
strA = strA + listA[i]
elif listA[i] == ' ':
listB.append(strA)
strA = ''
listB.reverse()
return ' '.join(listB)
if __name__=='__main__':
strs='pig loves dog'
print(Solution().reverseSentence(strs))
注意:
Python将某个列表转换成字符串 ' '.join(listB)
str() 是将某单个元素转换成字符
案例五
字符串移位练习题
注意:由于限定了额外空间复杂度为O(1),不能借助新的数组或字符串,只能原地调整
解题思路:
将左部分的字符逆序
将右部分的字符逆序
将整体字符逆序
def move(A,i):
A = Reverse(A, 0, i)
A = Reverse(A, i+1, len(A)-1)
A = Reverse(A, 0, len(A)-1)
return A
def Reverse(A,left,right): Python自定义逆序函数
A = list(A)
while(left<right):
A[left], A[right] = A[right], A[left]
left += 1
right -= 1
return ''.join(A)
案例六
拼接最小字典序练习题
思路一:比较单个字符串的字典顺序(错误)
思路二:比较两个字符串可结合之后的字典顺序(正确),让整体大的字符串顺序最小
class Solution():
def connect(self, strs):
if not strs:
return ''
for i in range(1,len(strs)):
for j in range(i):
if strs[i]+strs[j] < strs[j]+strs[i]:
strs[i],strs[j] = strs[j],strs[i]
return ''.join(strs)