无重复字符的最长子串
题目(Medium)
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
给定一个字符串,找出不含有重复字符的 最长子串 的长度。
示例:
给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3。
给定 "bbbbb" ,最长的子串就是 "b" ,长度是1。
给定 "pwwkew" ,最长子串是 "wke" ,长度是3。请注意答案必须是一个子串,"pwke" 是 子序列 而不是子串。
思路:
双指针,查找表,当遇到个第二个相同的字符时,就遍历前面p到i-1的数组,把第二个相同的字符出现的第一个位置之前的字符都在表里删掉,因为要断开了嘛,此时不连续了
import java.util.HashSet;
import java.util.Scanner;
public class 无重复字符的最长子串 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.next();
System.out.println(lengthOfLongestSubstring(s));
}
public static int lengthOfLongestSubstring(String s) {
char[] ch = s.toCharArray();
HashSet<Character> set = new HashSet<>();
int n = ch.length;
int max=0;
int sum=0;
int p=0;
for(int i=0;i<n;i++)
{
if(!set.contains(ch[i]))
{
set.add(ch[i]);
sum++;
}
else
{
max = Math.max(max,sum);
for(;p<i;p++)
{
if(ch[p]!=ch[i])
{
set.remove(ch[p]);
// System.out.println(p+" "+set.toString());
}
else
{
p++;
break;
}
}
sum=i-p+1;
// sum=set.size(); //记录sum都是对的,但这个性能差一些,因为调用了内部方法嘛
}
}
max = Math.max(max,sum);
return max;
}
}