Skip to content

Commit 2479d37

Browse files
author
vesper
committed
feat: 3. 无重复字符的最长子串
1 parent 78a6008 commit 2479d37

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
- [731. 我的日程安排表 II - Medium](./src/leetcode/misc/leet_zh_731/MyCalendarTwo.java)
2222
- [732. 我的日程安排表 III - Hard](./src/leetcode/misc/leet_zh_732/MyCalendarThree.java)
2323
- 【字符串】
24+
- [3. 无重复字符的最长子串 - Medium](src/leetcode/string/leet_zh_3/Solution.java)
2425
- [76. 最小覆盖子串 - Hard](src/leetcode/string/leet_zh_76/Solution.java)
2526
- [438. 找到字符串中所有字母异位词 - Medium](src/leetcode/string/leet_zh_438/Solution.java)
2627
- [无重复字符的最长子串 - Medium](src/leetcode_specialized/bytedance/string/longest_substring_without_repeating_characters/Solution.java)
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package leetcode.string.leet_zh_3;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
public class Solution {
7+
/*
8+
* Title: 3. 无重复字符的最长子串
9+
* Link : https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
10+
* Label: ["哈希表", "双指针", "字符串", "Sliding Window"]
11+
* Diff : Medium
12+
* Desc :
13+
* 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
14+
15+
示例 1:
16+
17+
输入: "abcabcbb"
18+
输出: 3
19+
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
20+
示例 2:
21+
22+
输入: "bbbbb"
23+
输出: 1
24+
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
25+
示例 3:
26+
27+
输入: "pwwkew"
28+
输出: 3
29+
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
30+
  请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
31+
32+
* 执行用时 : 9 ms
33+
* 内存消耗 : 39.4 MB
34+
* */
35+
36+
public int lengthOfLongestSubstring(String s) {
37+
int maxLength = 0;
38+
if (s.length() == 0) {
39+
return maxLength;
40+
}
41+
char c;
42+
int left = 0, right = 0;
43+
Map<Character, Integer> windows = new HashMap<>();
44+
while (right < s.length()) {
45+
c = s.charAt(right);
46+
if (!windows.containsKey(c)) {
47+
windows.put(c, right);
48+
if (maxLength < right - left + 1) {
49+
maxLength = right - left + 1;
50+
}
51+
} else {
52+
int index = windows.get(c) + 1;
53+
for (int i = left; i < index; i++) {
54+
char c2 = s.charAt(i);
55+
windows.remove(c2);
56+
}
57+
left = index;
58+
windows.put(c, right);
59+
}
60+
right++;
61+
}
62+
return maxLength;
63+
}
64+
65+
public static void main(String[] args) {
66+
Solution ss = new Solution();
67+
// System.out.println(ss.lengthOfLongestSubstring("abcabcbb"));
68+
// System.out.println(ss.lengthOfLongestSubstring("bbbbb"));
69+
// System.out.println(ss.lengthOfLongestSubstring("pwwkew"));
70+
System.out.println(ss.lengthOfLongestSubstring("tmmzuxt1z"));
71+
}
72+
}

0 commit comments

Comments
 (0)