LeetCode-0312
1071.字符串的最大公因子
def gcdOfStrings(str1,str2):
#反向查找,找到可以被整除的子串长度,判断子串是否满足多次连接
for i in range(min(len(str1),len(str2)),0,-1):
print(i,str1[:i])
if len(str1)%i ==0 and len(str2)%i ==0:
if str1[:i]*(len(str1)//i) == str1 and str1[:i]*(len(str2)//i) == str2:
return str1[:i]
return ""
#如果 str1 和 str2 拼接后等于 str2和 str1 拼接起来的字符串(注意拼接顺序不同),那么一定存在符合条件的字符串 X
def gcdOfStrings(str1,str2):
import math
gcd = math.gcd(len(str1),len(str2))
substr = str1[:gcd]
if str1 + str2 == str2+str1:
return substr
return ""
3.无重复字符的最长子串
def lengthOfLongestSubstring(s):
if s:
left,right = 0,1
maxlen =0
dic = []
dic.append(s[left])#存储已经见过的字符
while left<=right and right<len(s):
# print(dic,left,right,maxlen)
if s[right] not in dic:#判断是否出现过
dic.append(s[right])
maxlen = max(right-left+1,maxlen)
right += 1
else:
index = dic.index(s[right])
left += index+1 #出现过,移动left跳过该值
dic = dic[index+1:] #更新
return maxlen
else:
return 0
s = "pwwkew"
lengthOfLongestSubstring(s)
输出:
['p'] 0 1 0
['p', 'w'] 0 2 2
[] 2 2 2
['w'] 2 3 2
['w', 'k'] 2 4 2
['w', 'k', 'e'] 2 5 3
['k', 'e'] 3 5 3