Skip to content

Commit af81849

Browse files
authored
Merge pull request neetcode-gh#1928 from saip7795/sp/min-window-substring
Create: 0076-min-window-substring.rb
2 parents 5378a9e + 3a5138e commit af81849

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

ruby/0076-min-window-substring.rb

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
def min_window(s, t)
3+
4+
return "" if t == ""
5+
count_t = Hash.new(0)
6+
window = Hash.new(0)
7+
8+
t.each_char do |c|
9+
count_t[c] +=1
10+
end
11+
12+
have = 0
13+
need = count_t.length
14+
15+
res = [-1,-1]
16+
result_length = 9999999999
17+
l = 0
18+
(0..s.length-1).each do |r|
19+
c = s[r]
20+
window[c] +=1
21+
22+
have +=1 if ((count_t.keys.include?(c)) && (window[c] == count_t[c]))
23+
while(have == need)
24+
if (r-l+1) < result_length
25+
res = [l,r]
26+
result_length = (r-l+1)
27+
28+
end
29+
window[s[l]] -=1
30+
have -=1 if ((count_t.keys.include?(s[l])) && (window[s[l]] < count_t[s[l]]))
31+
l +=1
32+
end
33+
end
34+
l = res[0]
35+
r = res[1]
36+
if result_length != 9999999999
37+
return s[l..r]
38+
else
39+
return ""
40+
end
41+
end

0 commit comments

Comments
 (0)