classSolution: defreverseLeftWords(self, s: str, n: int) -> str: return s[n:] + s[:n] defreverseLeftWords(self, s: str, n: int) -> str: # 列表遍历拼接 res = [] for i inrange(n, len(s)): res.append(s[i]) for i inrange(n): res.append(s[i]) return''.join(res) defreverseLeftWords(self, s: str, n: int) -> str: # 字符串遍历拼接 res = ""# 字符为不可变对象,每轮都新建 for i inrange(n, len(s)): res += s[i] for i inrange(n): res += s[i] return res
classSolution: defminWindow(self, s: str, t: str) -> str: s_len, t_len = len(s), len(t) if s_len < t_len: return"" # 0 不删除 sdict, tdict = defaultdict(int), Counter(t) left, conut = 0, 0 res = "" for i inrange(s_len): sdict[s[i]] += 1 if sdict[s[i]] <= tdict[s[i]]: conut += 1 while left <= i and sdict[s[left]] > tdict[s[left]]: # 加一个A就减一个A...(无用后缀) sdict[s[left]] -= 1 left += 1 if conut == t_len: ifnot res or (i - left + 1 < len(res)): res = s[left:i + 1] return res
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defisPalindrome(self, s: str) -> bool: n = len(s) left, right = 0, n - 1 while left < right: while left < right andnot s[left].isalnum(): left += 1 while left < right andnot s[right].isalnum(): right -= 1 if left < right: if s[left].lower() != s[right].lower(): returnFalse left, right = left + 1, right - 1 returnTrue
给定一个非空字符串 s,请判断如果 最多
从字符串中删除一个字符能否得到一个回文字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defvalidPalindrome(self, s: str) -> bool: # 回溯, 广度优先 【字符串长度,暴搜必定超时】 defcheckPalind(l, r): while l < r: if s[l] != s[r]: returnFalse l += 1 r -= 1 returnTrue n = len(s) left, right = 0, n - 1 while left < right: if s[left] == s[right]: left += 1 right -= 1 else: return checkPalind(left + 1, right) or checkPalind(left, right - 1) returnTrue
给定一个字符串 s
,请计算这个字符串中有多少个回文子字符串。具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
classSolution: defcountSubstrings(self, s: str) -> int: # 双指针+中心扩散 result = 0 def_extend(s, i, j, n): res = 0 while i >= 0and j < n and s[i] == s[j]: # 确定中心点 i -= 1 j += 1 res += 1# 扩散过程也是答案 return res for i inrange(len(s)): result += _extend(s, i, i, len(s)) #以i为中心 result += _extend(s, i, i+1, len(s)) #以i和i+1为中心 return result
defcountSubstrings(self, s: str) -> int: # 动态规划 dp[i][j]: s[i:j] 是否为回文子串 # dp[i+1][j-1] -> dp[i][j] 遍历顺序 n = len(s) dp = [[False] * (n) for _ inrange(n)] ans = 0 for i inrange(n-1,-1,-1): for j inrange(i,n): if s[i] == s[j]: if j - i <= 1: ans += 1 dp[i][j] = True elif dp[i+1][j-1]: ans += 1 dp[i][j] = True return ans