目录
题目
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
代码
public static int lengthOfLongestSubstring(String s){
// 记录字符是否出现过
Set app = new HashSet();
int len = s.length();
// 双指针
// 右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动
int right = -1, res = 0 ;
for (int i = 0; i < len; i++) {
if (i != 0){
// 遍历下一位左指针
app.remove(s.charAt(i-1));
}
while (right + 1 < len && !app.contains(s.charAt(right + 1))){
// 移动右指针
app.add(s.charAt(right + 1));
++right;
}
// 最长无重复子字符串:下标【i,right】之间的字符串
res = Math.max(res, right - i + 1);
}
return res;
}
总结
1、滑动窗口;
2、HashSet去掉重复的元素;
完整测试代码
import java.util.HashSet;
import java.util.Set;
/**
* 无重复字符的最长子串
*
*/
public class LengthOfLongestSubstringSolution {
public static void main(String[] args) {
String s = "adfadfasdfs";
System.out.println(lengthOfLongestSubstring(s));
}
public static int lengthOfLongestSubstring(String s){
// 记录字符是否出现过
Set app = new HashSet();
int len = s.length();
// 双指针
// 右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动
int right = -1, res = 0 ;
for (int i = 0; i < len; i++) {
if (i != 0){
// 遍历下一位左指针
app.remove(s.charAt(i));
}
while (right + 1 < len && !app.contains(s.charAt(right + 1))){
// 移动右指针
app.add(s.charAt(right + 1));
++right;
}
// 最长无重复子字符串:下标【i,right】之间的字符串
res = Math.max(res, right - i + 1);
}
return res;
}
}