Find All Anagrams in a String
LeetCode 438 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Fixed window of len(p); compare frequency counts.
ನಾನು Find All Anagrams in a String (LeetCode 438) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Fixed Window ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Any anagram of p is a window of length |p| in s with the same letter counts. Slide a fixed-size window, update counts by adding the new character and removing the oldest, and compare with p's counts each step.
Approach
- 1
Count letters of p.
- 2
Add s[r] to the window counts.
- 3
If the window is too long, remove s[l] and advance l.
- 4
If counts match, record l.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ · ಮೊದಲ ಆಲೋಚನೆಯಿಂದ ಅಂತಿಮ ಪರಿಹಾರದವರೆಗೆ
Compare Counters.
Fixed-size arrays.
Counter windowPythonO(n) time
from collections import Counter
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
l=0
r=0
res=[]
p_counter = Counter(p)
window_counter=Counter()
while r<len(s):
#add the current char and increment the counter
window_counter[s[r]]+=1
#shrink it
if r-l+1 > len(p):
#adjust the l th char
if window_counter[s[l]]==1:
del window_counter[s[l]]
else:
window_counter[s[l]]-=1
l+=1
if window_counter==p_counter:
res.append(l)
r+=1
return res
from collections import Counter26-array windowPythonO(n·26) time · O(1) space
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(s)<len(p):
return []
l=0
r=0
res=[]
s_count=[0]*26
p_count=[0]*26
for char in p:
p_count[ord(char)-ord('a')]+=1
while r<len(s):
#add the current char and increment the counter
s_count[ord(s[r])-ord('a')]+=1
#shrink it
if r-l+1 > len(p):
#adjust the l th char
if s_count[ord(s[l])-ord('a')]==1:
s_count[ord(s[l])-ord('a')]=0
else:
s_count[ord(s[l])-ord('a')]-=1
l+=1
if s_count==p_count:
res.append(l)
r+=1
return resFind All Anagrams in a String — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Find All Anagrams in a String ಹಿಂದಿನ intuition ಏನು?
Any anagram of p is a window of length |p| in s with the same letter counts. Slide a fixed-size window, update counts by adding the new character and removing the oldest, and compare with p's counts each step.
Find All Anagrams in a String (LeetCode 438) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Count letters of p. 2. Add s[r] to the window counts. 3. If the window is too long, remove s[l] and advance l. 4. If counts match, record l.
Find All Anagrams in a String ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n · 26). Space: O(26). (Accepted approach: 26-array window.)
Find All Anagrams in a String ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Remove zero entries from a Counter, or the equality check fails.
Find All Anagrams in a String ಅನ್ನು ಪರಿಹರಿಸಲು ಒಂದಕ್ಕಿಂತ ಹೆಚ್ಚು ಮಾರ್ಗಗಳಿವೆಯೇ?
Counter window (O(n) time): Compare Counters. 26-array window (O(n·26) time · O(1) space): Fixed-size arrays.