forked from mengli/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestSubstringWithoutRepeatingCharacters.java
More file actions
Latest commit
40 lines (35 loc) · 935 Bytes
/
Copy pathLongestSubstringWithoutRepeatingCharacters.java
File metadata and controls
40 lines (35 loc) · 935 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
34
35
36
37
38
39
40
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;
else
returnresult;
}
}