Skip to content

Commit f808f0e

Browse files
author
weiy
committed
fix #3
1 parent bc5b546 commit f808f0e

File tree

1 file changed

+86
-2
lines changed

1 file changed

+86
-2
lines changed

DP/FindAllAnagramsInAString.py

Lines changed: 86 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,23 @@
7575
测试地址:
7676
https://leetcode.com/problems/find-all-anagrams-in-a-string/description/
7777
78+
2018/10/27 修正:
79+
80+
上次分析后是有不足的,可以AC只是因为这个题的测试用例很少。
81+
82+
问题出在上面分析的 2. 和 3. 中,
83+
重新梳理下:
84+
若没有存在于最后一个dp中,那么先判断是否有重复:
85+
1. 如果在 p 中,但不在上一个子问题的需求解里。
86+
2. 此时要找一个合适的 ·复活点·,直接上例子吧
87+
88+
s "cbdbcae"
89+
cbd b 当出现第二个 b 时,b不与之前分析后所找到的 c 相同,那么可以判定为要从 b 这个点开始复活了,但如果是的话那就找不到了。
90+
要复活的点是 从 b 之前的一个 d。 也就是复活点要在重复的那个字符后面开始,那么我们要做的就是把在它之前的字符给加回来。
91+
p "abcde"
92+
93+
待学习 Discuss 滑动窗口。
94+
7895
"""
7996
class Solution(object):
8097
def findAnagrams(self, s, p):
@@ -122,7 +139,75 @@ def findAnagrams(self, s, p):
122139

123140
dp = x
124141
else:
125-
if s[i] in _p and s[i] != s[i-1] and s[i] == s[i-len(p)+1]:
142+
if s[i] in _p:
143+
if s[i] != s[i-len(p)+sum(dp.values())]:
144+
for t in s[i-len(p)+sum(dp.values()):i]:
145+
if t == s[i]:
146+
break
147+
try:
148+
dp[t] += 1
149+
except:
150+
dp[t] = 1
151+
continue
152+
153+
x = _p.copy()
154+
if s[i] in x:
155+
x[s[i]] -= 1
156+
if not x[s[i]]:
157+
x.pop(s[i])
158+
dp = x
159+
160+
return result
161+
162+
163+
# 下面这个代码有瑕疵。
164+
class Solution(object):
165+
def findAnagrams(self, s, p):
166+
"""
167+
:type s: str
168+
:type p: str
169+
:rtype: List[int]
170+
"""
171+
172+
# p = sorted(p)
173+
if not s:
174+
return []
175+
_p = {}
176+
177+
for i in p:
178+
try:
179+
_p[i] += 1
180+
except:
181+
_p[i] = 1
182+
183+
result = []
184+
185+
x = _p.copy()
186+
if s[0] in _p:
187+
x[s[0]] -= 1
188+
if not x[s[0]]:
189+
x.pop(s[0])
190+
191+
dp = x
192+
if not dp:
193+
return [i for i in range(len(s)) if s[i] == p]
194+
195+
for i in range(1, len(s)):
196+
if s[i] in dp:
197+
t = dp
198+
t[s[i]] -= 1
199+
if not t[s[i]]:
200+
t.pop(s[i])
201+
202+
if not t:
203+
result.append(i-len(p)+1)
204+
x = {}
205+
_t = s[i-len(p)+1]
206+
x[_t] = 1
207+
208+
dp = x
209+
else:
210+
if s[i] in _p and s[i] != s[i-1] and s[i] == s[i-len(p)+sum(dp.values())]:
126211
continue
127212
x = _p.copy()
128213
if s[i] in x:
@@ -132,4 +217,3 @@ def findAnagrams(self, s, p):
132217
dp = x
133218

134219
return result
135-

0 commit comments

Comments
 (0)