- Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathLongestSubstringWithoutRepeatingCharacters.java
More file actions
Latest commit
33 lines (31 loc) · 987 Bytes
/
Copy pathLongestSubstringWithoutRepeatingCharacters.java
File metadata and controls
33 lines (31 loc) · 987 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
importjava.util.HashMap;
/**
* Given a string, find the length of the longest substring without repeating characters. For
* example, the longest substring without repeating letters for "abcabcbb" is "abc", which the
* length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
*/
publicclassLongestSubstringWithoutRepeatingCharacters {
publicintlengthOfLongestSubstring(Strings) {
if (s.length() == 0) return0;
inti = 0, j = 0;
intresult = 0;
HashMap<Integer, Integer> map = newHashMap<Integer, Integer>();
while (j < s.length()) {
Integerc = newInteger(s.charAt(j));
if (!map.containsKey(c)) {
map.put(c, j);
} else {
intlength = j - i;
if (result < length) {
result = length;
}
Integerindex = map.get(c);
i = Math.max(i, index + 1);
map.put(c, j);
}
j++;
}
if (result < j - i) returnj - i;
elsereturnresult;
}
}