I am doing one classic leet code problem: finding the longest non-repeating substring in a string. Though there are many similar problems on stack overflow. I scratched my head for hours couldn't know why my code produce this weird result. hoping that someone could tell me why my
I am doing it in Java
public static void main( String[] args )
{
String s= "wwhoamiUrektxineabcdefghijklmno";
longestNonRepeatStr(s);
}
public static void longestNonRepeatStr(String tstring) {
String str="";
String compare="";
List<String> list= new ArrayList<String>();
int biggest =0;
//find the nonrepeating string in each loop and add to list str
for (int i=0; i<tstring.length(); i++) {
for (int j=i; j<tstring.length()-1; j++) {
str+= tstring.charAt(j);
compare= Character.toString(tstring.charAt(j+1));
if (str.contains(compare)){
list.add(str);
str="";
break;
}
}
}
//find the longest nonrepeating string in the list
for (int i=0; i<list.size(); i++) {
if (list.get(biggest).length()< list.get(i).length()) {
biggest=i;
}
}
System.out.println(list);
System.out.println(list.get(biggest));
}
For input string
"wwhoamiUrektxineabcdefghijklmno"
output is
"abcdefghijklmnb"
but it is wrong, the last letter should be "o"