理论部分
- 用数组实现一个顺序的串结构。
- 为该串结构提供丰富的操作,比如插入子串、在指定位置移除给定长度的子串、在指定位置取子串、连接串、串匹配等。
练习部分
- 无重复字符的最长子串
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
示例1
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例2
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例3
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
代码:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
len_str=len(s)
final_len=[]
for i in range(len_str):
data1=s[i]
for j in range(i+1,len_str):
if s[j] not in data1:
data1=data1+s[j]
else:
break
final_len.append(len(data1))
if final_len==[]:
if s=='':
final_len.append(0)
else:
final_len.append(1)
return(max(final_len))
结果:
2. 串联所有单词的子串
https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/
给定一个字符串s和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
示例1
输入:
s = "barfoothefoobarman",
words = ["foo","bar"]
输出:[0,9]
解释:
从索引 0 和 9 开始的子串分别是 "barfoo" 和 "foobar" 。输出的顺序不重要, [9,0] 也是有效答案。
示例2
输入:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
输出:[]
代码:
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
l=[]
if(words==[]):return []
n=len(words[0])
q={}
for i in words:
if i in q:q[i]+=1
else:q[i]=1
for t in range(n):
d={}
a=t
b=t
while a+len(words)*n<=len(s):
word=s[b:b+n]
b=b+n
if(word not in words):
a=b
d.clear()
else:
if word in d:d[word]+=1
else:d[word]=1
while d[word]>q[word]:
d[s[a:a+n]]-=1
a=a+n
if b-a==len(words)*n:l.append(a)
return l
结果:
3. 替换子串得到平衡字符串
https://leetcode-cn.com/problems/replace-the-substring-for-balanced-string/
有一个只含有’Q’, ‘W’, ‘E’,'R’四种字符,且长度为 n的字符串。假如在该字符串中,这四个字符都恰好出现n/4次,那么它就是一个「平衡字符串」。
给你一个这样的字符串 s,请通过「替换一个子串」的方式,使原字符串 s变成一个「平衡字符串」。你可以用和「待替换子串」长度相同的任何其他字符串来完成替换。
请返回待替换子串的最小可能长度。
如果原字符串自身就是一个平衡字符串,则返回 0。
示例1:
输入:s = "QWER"
输出:0
解释:s 已经是平衡的了。
示例2:
输入:s = "QQWE"
输出:1
解释:我们需要把一个 'Q' 替换成 'R',这样得到的 "RQWE" (或 "QRWE") 是平衡的。
示例3:
输入:s = "QQQW"
输出:2
解释:我们可以把前面的 "QQ" 替换成 "ER"。
示例4:
输入:s = "QQQQ"
输出:3
解释:我们可以替换后 3 个 'Q',使 s = "QWER"。
代码:
class Solution:
def balancedString(self, s: str) -> int:
cnt = collections.Counter(s)
res = n = len(s)
i, avg = 0, n//4
for j, c in enumerate(s):
cnt[c] -= 1
while i < n and all(avg >= cnt[x] for x in 'QWER'):
res = min(res, j - i + 1)
cnt[s[i]] += 1
i += 1
return res
结果: