-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSolution.java
More file actions
33 lines (29 loc) · 839 Bytes
/
Solution.java
File metadata and controls
33 lines (29 loc) · 839 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
31
32
33
/*
* 3. Longest Substring Without Repeating Characters
* https://leetcode.com/problems/longest-substring-without-repeating-characters/
* */
import java.util.HashSet;
import java.util.Set;
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.isEmpty()) {
return 0;
}
int result = 1;
int i = 0;
int j = 1;
Set<Character> set = new HashSet<>();
while (i < s.length() && j < s.length()) {
if (!set.contains(s.charAt(j)) && s.charAt(i) != s.charAt(j)) {
set.add(s.charAt(j));
result = Math.max(result, j - i + 1);
j += 1;
} else {
set = new HashSet<>();
i += 1;
j = i + 1;
}
}
return result;
}
}