RT
我用了2重for循环,应该不是最优。谁有好一点的改进。求请各路大神赐教!!!
public class SubStr {
public static void main(String[] args) {
String input="abdabbsabcdefgssdwesskkkjl";
StringBuffer output = new StringBuffer();
int length=0;
int maxlength=0;
List list = new ArrayList<String>();
for(int i=0;i<input.length();i++){
for(int j=i;j<input.length();j++){
char ch = input.charAt(j);
if(!list.contains(ch)){
list.add(ch);
length++;
}else{
break;
}
}
if(length>=maxlength){
output.delete(0, output.length());
maxlength=length;
Iterator it = list.iterator();
while(it.hasNext()){
output.append(it.next());
}
}
length =0;
list.clear();
}
System.out.println(maxlength);
System.out.println(output.toString());
}
}
------解决思路----------------------
什么叫不是完整的子串?
什么叫原串中 完整的子串?
------解决思路----------------------
import java.util.*;
public class SubStr {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
while(cin.hasNext()) {
String str = cin.nextLine();
launch(str);
}
}
public static void launch(String str) {
StringBuilder sb = new StringBuilder();
int length = 0;
int maxLength = 0;
String output = "";
int start = 0;
for(int i=0; i<str.length(); i++) {
if(sb.indexOf((""+str.charAt(i)))==-1) {
sb.append(str.charAt(i));
length ++;
} else {
if(length > maxLength) {
output = sb.toString();
maxLength = length;
}
start = sb.indexOf(""+str.charAt(i))+1;
sb = sb.delete(0, start);
sb.append(str.charAt(i));
length = length-start+1;
}
}
if(length > maxLength) {
output = sb.toString();
maxLength = length;
}
System.out.println(output);
}
}