Back to course home
0% completed
Vote For New Content
Simpler solution
Mohammed Dh Abbas
Jul 11, 2024
from collections import Counter class Solution: def findSubstring(self, text, pattern): counter_freq = Counter(pattern) text_freq = {} result = "" short_len = float('inf') # method that checks if text map contains the counter map def found(text_freq, counter_freq): for char, freq in counter_freq.items(): if char not in text_freq or freq > text_freq[char]: return False return True i = 0 j = 0 while i < len(text): # append i frequency to the text map and move i text_freq[text[i]] = text_freq.get(text[i], 0) text_freq[text[i]] += 1 i += 1 # while we can find the pattern in the text while found(text_freq, counter_freq): # if we found shorter string that has the pattern if i - j + 1 < short_len: short_len = i - j + 1 result = text[j:i] # remove j frequency from the text map and move j text_freq[text[j]] -= 1 if text_freq[text[j]] == 0: del text_freq[text[j]] j += 1 return result;
0
0
Comments
Comments
On this page