-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhot100_3.java
More file actions
43 lines (30 loc) · 1012 Bytes
/
Copy pathhot100_3.java
File metadata and controls
43 lines (30 loc) · 1012 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
41
42
43
import java.util.*;
/**无重复字符的最长子串
* 输入:abcabcbb 输出:3
*/
public class hot100_3 {
public static int lengthOfLongestSubstring(String s) {
// 存储字符最后出现的位置
HashMap<Character, Integer> map = new HashMap<>();
int left = 0;
int maxLen = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
// 如果字符重复
// 并且重复字符在窗口内部
if (map.containsKey(c) && map.get(c) >= left) {
left = map.get(c) + 1;
}
// 更新字符位置
map.put(c, right);
// 更新最大长度
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(lengthOfLongestSubstring(s));
}
}