Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a25a314

Browse files
MinimumWindowSubstring o(n2) implementation
1 parent 13e8598 commit a25a314

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package java_problem.slidewindow;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class MinimumWindowSubstring {
7+
public static void main(String args[]) {
8+
System.out.println(minWindow("ADOBECODEBANC", "ABC"));
9+
}
10+
11+
public static String minWindow(String s, String t) {
12+
int n1 = s.length();
13+
int n2 = t.length();
14+
if (n2 > n1) return "";
15+
16+
String minWindow = "";
17+
List<Character> ls = new ArrayList<>();
18+
StringBuilder sb = new StringBuilder();
19+
20+
for (int r = 0; r < n1; r++) {
21+
ls.add(s.charAt(r));
22+
sb.append(s.charAt(r));
23+
24+
// Check if the current window contains all characters of t
25+
while (containsAll(ls, t)) {
26+
if (minWindow.isEmpty() || sb.length() < minWindow.length()) {
27+
minWindow = sb.toString();
28+
}
29+
ls.remove(0); // Remove the leftmost character from the window
30+
sb.deleteCharAt(0); // Remove the leftmost character from the StringBuilder
31+
}
32+
}
33+
34+
return minWindow;
35+
}
36+
37+
// Helper function to check if all characters in t are present in ls
38+
private static boolean containsAll(List<Character> ls, String t) {
39+
List<Character> temp = new ArrayList<>(ls);
40+
for (char c : t.toCharArray()) {
41+
if (temp.contains(c)) {
42+
temp.remove((Character) c); // Remove the character from temp
43+
} else {
44+
return false; // If a character is missing, return false
45+
}
46+
}
47+
return true;
48+
}
49+
50+
51+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /