每日leetcode4.16(扰乱字符串)
87. 扰乱字符串(hard)
三维dp,四维运算,从长度为1开始向上增加
class Solution:
def isScramble(self, s1: str, s2: str) -> bool:
l = len(s1)
dp = [[[0] * l for i1 in range(l)] for i2 in range(l)]
for p in range(l):
for i in range(l - p):
for j in range(l - p):
if p == 0:
if s1[i] == s2[j]:
dp[p][i][j] = 1
for k in range(p):
if (dp[k][i][j] and dp[p - k - 1][i + k + 1][j + k + 1]) or (dp[k][i][j + p - k] and dp[p - k - 1][i + k + 1][j]):
dp[p][i][j] = 1
break
return dp[l - 1][0][0] == 1
3 无重复字符的最长字串
本题要在O(n)内解决,滑动窗口,用一个dict记录重复字符串的位置
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
l = len(s)
mp = {}
i = 0
j = 0
ans = 0
while j < l:
while j < l and (mp.get(s[j]) is None or mp[s[j]] == -1):
mp[s[j]] = j
j += 1
ans = max(ans, j - i)
while j < l and i <= mp[s[j]]:
mp[s[i]] = -1
i += 1
return ans