Skip to content

Commit d07aa46

Browse files
committed
Add finding longest substring without repeating chars problem
1 parent d8df121 commit d07aa46

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Sliding window: TC: O(n), SC: O(n)
2+
package java1.algorithms.strings;
3+
4+
import java.util.HashSet;
5+
6+
public class longestSubstringWithoutRepeatingChar {
7+
private static int longestSubstringLengthWithoutRepeatingChar(String str) {
8+
HashSet<Character> hashset = new HashSet<>();
9+
int left = 0, max = 0;
10+
11+
for(int right = 0; right < str.length(); right++) {
12+
while(hashset.contains(str.charAt(right))){
13+
hashset.remove(str.charAt(left));
14+
left++;
15+
}
16+
hashset.add(str.charAt(right));
17+
max = Math.max(max, hashset.size());
18+
}
19+
return max;
20+
}
21+
22+
public static void main(String[] args) {
23+
String string1 = "abcabcbbaa";
24+
System.out.println(longestSubstringLengthWithoutRepeatingChar(string1));
25+
String string2 = "aaaaaaa";
26+
System.out.println(longestSubstringLengthWithoutRepeatingChar(string2));
27+
}
28+
29+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Sliding window: TC: O(n), SC: O(n)
2+
function longestSubstringLengthWithoutRepeatingChar(string) {
3+
let set = new Set();
4+
let left = max = 0;
5+
6+
for(let right = 0; right < string.length; right++) {
7+
while(set.has(string[right])) {
8+
set.delete(string[left]);
9+
left++;
10+
}
11+
set.add(string[right]);
12+
max = Math.max(max, set.size);
13+
}
14+
return max;
15+
}
16+
17+
let string1 = "abcabcbbaa";
18+
console.log(longestSubstringLengthWithoutRepeatingChar(string1));
19+
let string2 = "aaaaaaa";
20+
console.log(longestSubstringLengthWithoutRepeatingChar(string2));

0 commit comments

Comments
 (0)