-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3.无重复字符的最长子串.java
43 lines (32 loc) · 1.23 KB
/
3.无重复字符的最长子串.java
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
41
42
/*
* @lc app=leetcode.cn id=3 lang=java
*
* [3] 无重复字符的最长子串
*/
// @lc code=start
import java.util.HashMap;
import java.util.Map;
class Solution {
public int lengthOfLongestSubstring(String s) {
return lengthOfLongestSubstringSlideWindow(s);
}
int lengthOfLongestSubstringSlideWindow(String s) {
// slide window and hashtable, from leetcode official and improvement in comments
// use a hashmap to store last index of an charactor.
// when window end comes to the s end, we will get the answer.
int windowLeft = -1;
int ans = 0;
Map<Character, Integer> lastIndex = new HashMap<>();
for (int windowRight = 0; windowRight < s.length(); windowRight++) {
Character cToProc = s.charAt(windowRight);
// if last index of current charactor key is in the window, it means there is a duplicated char in window now.
if (lastIndex.containsKey(cToProc) && lastIndex.get(cToProc) > windowLeft) {
windowLeft = lastIndex.get(cToProc);
}
lastIndex.put(cToProc, windowRight);
ans = Math.max(ans, windowRight - windowLeft);
}
return ans;
}
}
// @lc code=end