-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestsubstring.java
More file actions
30 lines (28 loc) · 913 Bytes
/
longestsubstring.java
File metadata and controls
30 lines (28 loc) · 913 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Given a string s, find the length of the longest substring without repeating characters.
// Input: s = "abcabcbb"
// Output: 3
// Explanation: The answer is "abc", with the length of 3.
//SLIDING WINDOW METHOD
import java.util.*;
import java.lang.Math.*;
public class longestsubstring {
public static int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
// try to extend the range [i, j]
if (!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
}
else {
set.remove(s.charAt(i++));
}
}
return ans;
}
public static void main(String[] args){
System.out.println(lengthOfLongestSubstring("abccabcbb"));
}
}