获得最长的无重复子串

时间:2022-12-22 15:48:11

题目:给定一个字符串string,找出string中无重复字符的最长子串。

举例:

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 asubstring, "pwke" is a subsequence and not a substring.

public class MaxSubLen{

//获得最长的无重复子串
public static int GetMaxSubLen(String s)
{
if(s==null||s.equals(""))
{
return 0;
}
char[]chs=s.toCharArray();
int[]dp=new int[256];
int maxlen=0; //保存最长的长度
int i=0;
int j=0;
for( ;j<chs.length;j++)
{
while(dp[chs[j]]==1)
{
dp[chs[i]]=0;
++i;
}
dp[chs[j]]=1;
maxlen=maxlen>(j-i+1)?maxlen:j-i+1;

}
for(int k=i;k<j;k++)
{
System.out.print(chs[k]+" ");
}
System.out.println();
return maxlen;
}

public static void main(String[]args)
{

String str1="bbbbb";
String str2="pwwkew";
String str3="abcd";
System.out.println("最长不重复子串长度:"+GetMaxSubLen(str1));
System.out.println("最长不重复子串长度:"+GetMaxSubLen(str2));
System.out.println("最长不重复子串长度:"+GetMaxSubLen(str3));

}
}

获得最长的无重复子串