Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Minimum Window Substring.cpp #27

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions Sliding Window/Minimum Window Substring.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,39 @@ class Solution {
return minWindow == INT_MAX ? "" : s.substr(minStart, minWindow);
}
};

// Java code:
class Solution {
public String minWindow(String s, String t) {
int n = s.length();
Map<Character, Integer> mp = new HashMap<>();
for(char ch : t.toCharArray()) {
mp.put(ch, mp.getOrDefault(ch, 0) + 1);
}
int requiredCount = t.length();
int i = 0, j = 0;
int minStart = 0;
int minWindow = Integer.MAX_VALUE;
while(j < n) {
char ch_j = s.charAt(j);
if(mp.getOrDefault(ch_j, 0) > 0)
requiredCount--;
mp.put(ch_j, mp.getOrDefault(ch_j, 0) - 1);
while(requiredCount == 0) {
if(minWindow > j - i + 1) {
minWindow = j - i + 1;
minStart = i;
}
char ch_i = s.charAt(i);
mp.put(ch_i, mp.get(ch_i) + 1);
if(mp.get(ch_i) > 0)
requiredCount++;
i++;
}
j++;
}
return minWindow == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minWindow);
}
}