给定一个字符串,找出不含有重复字符的最长子串的长度。
例:给定:abcabcbb,没有重复字符的最长子串是“abc",则长度就是3
给定"bbbbbb",最长的子串是b,长度是1
给定"pwwkew",最长子串是"wke",长度是3.
方法一:分析:找出不含有重复字符的最长子串的长度,当set集合中本来没有包含这个字符时,将这个字符添加到set集合中。将相同的移出。返回最大长度。
代码:
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
//找出不含有重复字符的最长子串的长度
public class LongestString {
public static int longestString(String str) {
Set<Character> set = new HashSet<>();
int i = 0, j = 0,result = 0;
while (i < str.length() && j < str.length()) {
if (!set.contains(str.charAt(j))) {
set.add(str.charAt(j++));
result = Math.max(result, j - i);
} else {
set.remove(str.charAt(i++));
}
}
return result;
}
public static void main(String[] args) {
Scanner scan =new Scanner(System.in);
System.out.println("please input the String: ");
String str=scan.nextLine();
System.out.println(longestString(str));
}
}
运行结果:
方法二:
分析:
代码:
import java.util.Scanner;
public class LongestString1 {
public static int LongestSubstring(String str){
int maxlength=0;
int start=0;
int pos;
String currency="";
for(int i=0,j=0;i<str.length();i++){
char a[] =str.toCharArray();
if(currency.indexOf(str.charAt(i))!=-1){
if(currency.length()>maxlength){
maxlength=currency.length();
}
pos=currency.indexOf(str.charAt(i));
currency=str.substring(start+currency.indexOf(str.charAt(i))+1,i+1);
start=start+pos+1; //start记录截取字符串开头在原字符串的位置
}
else{
currency=currency+str.charAt(i);
if(currency.length()>maxlength){
maxlength=currency.length();
}
}
}
return maxlength;
}
public static void main(String[] args) {
Scanner scan =new Scanner(System.in);
System.out.println("please input the String: ");
String str=scan.nextLine();
System.out.println(LongestSubstring(str));
}
}