Skip to content

Commit 4517a77

Browse files
committed
滑动窗口法,0003,无重复字符的最长子串
哈希表加上滑动窗口法
1 parent 7baf2f8 commit 4517a77

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
|----|----|----|----|
55
|[0001](https://leetcode-cn.com/problems/two-sum/)|两数之和|简单|[top](top)|
66
|[0002](https://leetcode-cn.com/problems/add-two-numbers/)|两数相加|中等|[top](top)|
7-
|[0003](https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/)|无重复字符的最长子串|中等|[top](top)|
7+
|[0003](https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/)|无重复字符的最长子串|中等|[top](top) [sliding window](sliding_window)|
88
|[0005](https://leetcode-cn.com/problems/longest-palindromic-substring/)|最长回文子串|中等|[top](top)|
99
|[0008](https://leetcode-cn.com/problems/string-to-integer-atoi/)|字符串转换整数 (atoi)|中等|[top](top)|
1010
|[0011](https://leetcode-cn.com/problems/container-with-most-water/)|盛最多水的容器|中等|[top](top)|

sliding_window/Lc0003Solution.java

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package sliding_window;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
public class Lc0003Solution {
7+
public int lengthOfLongestSubstring(String s) {
8+
if (s == null || s.length() == 0) {
9+
return 0;
10+
}
11+
int start = 0, ret = 0;
12+
Map<Character, Integer> map = new HashMap<>();
13+
for (int i = 0; i < s.length(); i++) {
14+
char c = s.charAt(i);
15+
if (map.containsKey(c)) {
16+
start = Math.max(start, map.get(c) + 1);
17+
}
18+
ret = Math.max(ret, i - start + 1);
19+
map.put(c, i);
20+
}
21+
return ret;
22+
}
23+
24+
public static void main(String[] args) {
25+
Lc0003Solution solution = new Lc0003Solution();
26+
String s = "abcabc";
27+
System.out.println(solution.lengthOfLongestSubstring(s));
28+
s = "";
29+
System.out.println(solution.lengthOfLongestSubstring(s));
30+
s = "aaaa";
31+
System.out.println(solution.lengthOfLongestSubstring(s));
32+
s = "pwwkew";
33+
System.out.println(solution.lengthOfLongestSubstring(s));
34+
}
35+
}

sliding_window/README.md

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
## Sliding Window
2+
|题号|题目|难度|在本目录|
3+
|----|----|----|----|
4+
|0003|无重复字符的最长子串|中等||

0 commit comments

Comments
 (0)