ID | Title | Difficulty | |
---|---|---|---|
Loading... |
3. Longest Substring Without Repeating Characters
Medium
LeetCode
Hash Table, String, Sliding Window
Problem
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints:
- $0 <= s.length <= 5 * 10^4$
- s consists of English letters, digits, symbols and spaces.
Code
class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character, Integer> map = new HashMap<>();
int maxLen = 0;
int j = 0;
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(map.containsKey(c)){
// WAABCWD 此时会发生currHead比map.get(s.charAt(w))+1大的情况
// index 0 1 2 3 4 5 6
// W A A B C W D
// 当currHead在位置2,i在位置5时,发现了重复
// 但是这时currHead的位置比
// map.get('W') + 1 = 1要大,此时不能取0,
// 而是要让currHead保持当前的位置
// 总结起来就是currHead只能增加不能减少
j = Math.max(j, map.get(c) + 1);
}
maxLen = Math.max(maxLen, i - j + 1);
map.put(c, i);
}
return maxLen;
}
}
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
start = res = 0
hm = {}
for i, c in enumerate(s):
if c in hm:
start = max(start, hm[c] + 1) # 不能往回走
res = max(res, i - start + 1)
hm[c] = i
return res
按 <- 键看上一题!
2. Add Two Numbers
按 -> 键看下一题!
4. Median of Two Sorted Arrays