来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
描述
给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,”pwke” 是一个子序列,不是子串。
题解
滑动窗口
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0, i = 0, j = 0;
Set<Character> set = new HashSet<>();
while (i < n && j < n) {
if (!set.contains(s.charAt(j))) {
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
} else {
set.remove(s.charAt(i++));
}
}
return ans;
}
}
复杂度分析
- 时间复杂度:
,在最糟糕的情况下,每个字符都将被i和j访问;
- 空间复杂度:
。滑动窗口需要
的空间,其中k表示Set的大小。而Set的大小取决于字符串n的大小以及字符集m的大小;
优化滑动窗口
HashMap
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0, j = 0; j < n; j++) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(i, map.get(s.charAt(j)));
}
map.put(s.charAt(j), j + 1);
ans = Math.max(ans, j - i + 1);
}
return ans;
}
}
Array
class Solution {
public int lengthOfLongestSubstring(String s) {
int ans = 0, n = s.length();
int[] index = new int[128];
for (int i = 0, j = 0; j < n; j++) {
i = Math.max(i, index[s.charAt(j)]);
ans = Math.max(ans, j - i + 1);
index[s.charAt(j)] = j + 1;
}
return ans;
}
}
复杂度分析
- 时间复杂度:
,索引j将会迭代n次。
- 空间复杂度(HashMap):
,与之前的方法相同。
- 空间复杂度(Table):
,m是字符集的大小。