LeetCode3-无重复字符的最长字串

题目链接

英文链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/

中文链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

题目详述

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

1
2
3
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:

1
2
3
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

示例 3:

1
2
3
4
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

题目详解

滑动窗口。

  • 遍历字符串,运用 HashMap 存储当前字符到索引的映射。
  • 如果 HashMap 中存在该字符,说明之前出现过,滑动窗口从该字符的下一个位置开始。
  • 因为出现过字符的下一个位置可能不在滑动窗口内,还需要与滑动窗口的起始位置进行比较,取二者最大值。
  • 遍历过程中更新最大值,遍历结束后返回即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class LeetCode_00003 {

public static int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>();
int res = 0;
int b = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (map.containsKey(c)) {
b = Math.max(b, map.get(c) + 1);
}
res = Math.max(res, i - b + 1);
map.put(c, i);
}
return res;
}
}