Skip to content

Commit 8e5e7f5

Browse files
committed
[add] LeetCode 3. Longest Substring Without Repeating Characters
1 parent 2112fd5 commit 8e5e7f5

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

algorithms-leetcode/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ Leetcode problems classified by company:
2929
|:----|:----|:----|:----|:----|
3030
|1|Two Sum|Easy|Hash Table||
3131
|2|Add Two Numbers|Medium|Linked List||
32+
|3|Longest Substring Without Repeating Characters|Medium|Sliding Window,Hash Table||
3233
|5|Longest Palindromic Substring|Medium|Dynamic Programming/Two Pointers|一题多解|
3334
|6|Zigzag Conversion|Medium||一题多解TODO|
3435
|10|Regular Expression Matching|Hard|||
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.brianway.learning.algorithms.leetcode.medium;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
/**
7+
* LeetCode 3. Longest Substring Without Repeating Characters
8+
* Question: https://leetcode.com/problems/longest-substring-without-repeating-characters/
9+
* 关键题设: 无
10+
* * @auther brian
11+
*
12+
* @since 2022/11/30 23:37
13+
*/
14+
public class LongestSubstringWithoutRepeatingCharacters {
15+
16+
public int lengthOfLongestSubstring(String s) {
17+
return 0;
18+
}
19+
20+
/**
21+
* 滑动窗口+hash表
22+
*
23+
* 测试用例:"tmmzuxt"
24+
*/
25+
public class LongestSubstringWithoutRepeatingCharacters0 extends LongestSubstringWithoutRepeatingCharacters {
26+
@Override
27+
public int lengthOfLongestSubstring(String s) {
28+
char[] chars = s.toCharArray();
29+
Map<Character, Integer> exist = new HashMap<>();
30+
int maxLen = 0;
31+
int start = 0;
32+
33+
for (int i = 0; i < chars.length; i++) {
34+
Integer lastIndex = exist.get(chars[i]);
35+
if (lastIndex == null || lastIndex < start) {
36+
// 未出现过,或者出现在左指针之前,直接计算length
37+
maxLen = Math.max(i - start + 1, maxLen);
38+
} else {
39+
// 当前chars[i]出现在start后,则需要右移start
40+
start = lastIndex + 1;
41+
}
42+
exist.put(chars[i], i);
43+
}
44+
return maxLen;
45+
}
46+
}
47+
48+
}

0 commit comments

Comments
 (0)