HashSet
‘Longest Substring Without Repeating Characters’ in LeetCode (Medium)
📌 Problem
https://leetcode.com/problems/longest-substring-without-repeating-characters/
📌 Answer
The point
- HashSet.contains(Object)
- Object ex. Character, String…
String.charAt(int index)
- import java.lang.Math;
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
import java.util.Set;
import java.util.HashSet;
import java.lang.Math;
class Solution {
public int lengthOfLongestSubstring(String s) {
int i = 0, j = 0, max = 0;
Set<Character> set = new HashSet<>();
while (j < s.length()) { // make the set without duplication
// if there is no duplicate element in set
if (!set.contains(s.charAt(j))) {
set.add(s.charAt(j++)); // add to set
max = Math.max(max, set.size()); // get max length
}
else set.remove(s.charAt(i++)); // if not, remove the duplicate element in set
}
return max;
}
}
/**
[Question]
- find the length of the longest substring without repeating characters.
**/
Comments powered by Disqus.