给定一个字符串,请找出其中无重复字符的最长子字符串。
样例
例如,在"abcabcbb"中,其无重复字符的最长子字符串是"abc",其长度为 3。
对于,"bbbbb",其无重复字符的最长子字符串为"b",长度为1。
挑战
样例
例如,在"abcabcbb"中,其无重复字符的最长子字符串是"abc",其长度为 3。
对于,"bbbbb",其无重复字符的最长子字符串为"b",长度为1。
挑战
O(n) 时间
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* 给定一个字符串,请找出其中无重复字符的最长子字符串。
样例
例如,在"abcabcbb"中,其无重复字符的最长子字符串是"abc",其长度为 3。
对于,"bbbbb",其无重复字符的最长子字符串为"b",长度为1。
挑战
O(n) 时间
*
* @author Dell
*
*/
public class Test384 {
public static int lengthOfLongestSubstring(String s)
{
Map<Character,Integer> map=new HashMap<>();
int[] pre=new int[s.length()];
char[] s1=s.toCharArray();
for(int i=0;i<s1.length;i++)
{
Integer temp=map.get(s1[i]);
if(temp==null)
{
pre[i]=i==0? 1: pre[i-1]+1;
map.put(s1[i], i);
}
else
{
int apos=temp+1;
int cl=pre[i-1];
int bpos=i-cl;
if(apos>=bpos)
pre[i]=i-apos+1;
else
pre[i]=i-bpos+1;
map.put(s1[i], i);
}
}
int max=0;
for(int i=0;i<pre.length;i++)
{
if(pre[i]>max)
max=pre[i];
}
return max;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
System.out.println(lengthOfLongestSubstring(s));
}
}