string " ABCABCBB "is" ABC ", which the length is 3. For "bbbbb" the longest substring are "B", with the length of 1.
Initial solution:
Idea: To find out all successive substrings, and then to determine whether each substring has duplicate elements
If the original string length is n, the number of all substrings is C (n,2) = n+n-1+...+1;
Public classSolution { Public intlengthoflongestsubstring (String s) {intLength =s.length (); BooleanReflag =false; intMax = 0; List<String> lists =NewArraylist<string> (); for(inti=0; i<length; i++) { for(intj=i+1; j<length; J + +) {Lists.add (s.substring (i,j+1)); } } for(String ssub:lists) {Reflag=false; for(inti=0; I<ssub.length (); i++){ Charc =Ssub.charat (i); if(Ssub.indexof (c,i+1)!=-1) {Reflag=true; Break; } } if(!Reflag) { intSublen =ssub.length (); if(Sublen >max) {Max=Sublen; } } } returnMax; } }
View Code
Public Static voidMain (string[] args) {String s= "Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789!\" #$%& "; BooleanReflag =false; intmax = 1; List<String> lists=NewArraylist<string>(); intLength =s.length (); for(inti=0; i<length; i++) { for(intj=i+1; j<length; J + +) {Lists.add (S.substring (i, J+1)); } } for(String subs:lists) {Reflag=false; for(inti=0; I<subs.length (); i++){ Charc =Subs.charat (i); if(Subs.indexof (c, i+1)!=-1) {Reflag=true; Break; } } if(!Reflag) { intSpace =subs.length (); if(Space >max) {Max=space; }}} System.out.println (max); System.out.println (Lists.size ()); System.out.println (Lists.tostring ()); }
This method does not pass the Leetcode test, but is logically correct, and for a particularly long string, a timeout error is indicated.
Improved method:
Edge find substring to determine if the substring repeats.
Longest Substring without repeating Characters2015 June 9