1.无重复字符的最长子串

def MaxSubStringLength(self,string):
start = 0
maxlen  = 0
maxsubstring = {}
for i in range(len(string)):
cur = string[i]
if cur in maxsubstring.keys():
pre = maxsubstring[cur]
if pre + 1 > start:
start = pre + 1
maxsubstring[cur] = i
else:
maxsubstring[cur] = i
if i - start + 1 >maxlen:
maxlen = i - start + 1
return maxlen


2.串联所有单词的子串

class Soultion(object):
"""docstring for Soultion"""
def findSubString(self,s,words):
if not s or words == []:
return []

lenstr = len(s)
lenword = len(words[0])
lensubstr = len(words)*lenword
times = {}
#统计words中各词出现的频率
for word in words:
if word in times:
times[word] += 1
else:
times[word] = 1

#存储结果
ans = []
for i in range(min(lenword,lenstr - lensubstr+1)):
return ans

wordstart = strstart
curr = {}
while strstart +lensubstr <= lenstr:
word = s[wordstart:wordstart+lenword]
wordstart += lenword
if word not in times:
strstart = wordstart
curr.clear()
else:
if word in curr:
curr[word] += 1
else:
curr[word] = 1
while curr[word] > times[word]:
curr[s[strstart:strstart+lenword]] -= 1
strstart += lenword
if wordstart - strstart == lensubstr:
ans.append(strstart)
return ans


3.替换字串得到平衡字串

def balanceString(s):
strlen = len(s)
cnt ,avg = [None] * (n+1),n//4
count[0] = {'Q':0,'W':0,'E':0,'R':0}
for i,v in enumerate(s):
cnt[i+1] = {k:v for k,v in cnt[i].items()}
cnt[i+1][v] += 1

def check(x):
for st in range(n-x+1):
t = {k:cnt[n][k] -cnt[st+x][k] + cnt[st][k] for k in cnt[0].keys()}
if all(avg >= t[x] for x in 'QWER'):
return True
return False

left,right = 0, n
while left < right:
mid = left+right >>1
if check(mid):
right = mid
else:
left = mid + 1
return left



©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客