Skip to content

Commit 247b15b

Browse files
committed
0008: Length of Longest Substring
1 parent c075efc commit 247b15b

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

0008/Solution.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.util.HashSet;
2+
3+
public class Solution {
4+
public int lengthOfLongestSubstring(String s) {
5+
int n = s.length();
6+
int longest = 0;
7+
int i = 0, j = 0;
8+
HashSet<Character> set = new HashSet<>();
9+
while (i < n && j < n) {
10+
11+
if (!set.contains(s.charAt(j))) {
12+
set.add(s.charAt(j));
13+
j++;
14+
longest = Math.max(longest, j - i);
15+
} else {
16+
set.remove(s.charAt(i));
17+
i++;
18+
}
19+
}
20+
return longest;
21+
}
22+
23+
public static void main(String[] args) {
24+
Solution sol = new Solution();
25+
26+
System.out.println("Expected 3 - Ans " + sol.lengthOfLongestSubstring("dvdf"));
27+
System.out.println("Expected 1 - Ans " + sol.lengthOfLongestSubstring("c"));
28+
System.out.println("Expected 3 - Ans " + sol.lengthOfLongestSubstring("abcabcbb"));
29+
System.out.println("Expected 1 - Ans " + sol.lengthOfLongestSubstring("bbbbb"));
30+
System.out.println("Expected 3 - Ans " + sol.lengthOfLongestSubstring("pwwkew"));
31+
// https://leetcode.com/problems/longest-substring-without-repeating-characters/tabs/description
32+
33+
}
34+
}

0 commit comments

Comments
 (0)