题目描述:
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例:
输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
题目链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
解答:
1、暴力**
思路简单,即针对于给出的串,依次遍历串中的所有子串,并判断该子串是否存在重复的字符,并记录当前最长的子串长度即可。
图示:
2、滑动窗口
即针对于已经做过比较的子串不重复比较,如果从索引 i 到 j - 1 之间的子字符串 s_{ij}已经被检查为没有重复字符。我们只需要检查 s[j]对应的字符是否已经存在于子字符串 s_{ij}中。
图示:
java代码:
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
// try to extend the range [i, j]
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;
}
}