Given a string, find the length of thelongest substringwithout repeating characters.

Examples:

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 asubsequenceand not a substring.



publicclassT{publicstaticvoidmain(String[]args){Strings1="pwwkew";Strings2="abcabcbb";Strings3="dvdf";Strings4="bbbb";System.out.println(lengthOfLongestSubstring(s1));}publicstaticintlengthOfLongestSubstring(Strings){intmaxlength=0;intleftIndex=0;intrightIndex=0;while(rightIndex<s.length()){chartarget=s.charAt(rightIndex);intmark=-1;for(inti=leftIndex;i<rightIndex;i++){if(s.charAt(i)==target){mark=i+1;break;}}if(mark!=-1){if((rightIndex-leftIndex)>maxlength){maxlength=(rightIndex-leftIndex);}leftIndex=mark;rightIndex=mark;}else{rightIndex++;}}if((rightIndex-leftIndex)>maxlength){maxlength=(rightIndex-leftIndex);}returnmaxlength;}}



另附网上的答案一则.
http://www.cnblogs.com/grandyang/p/4480780.html

publicclassSolution{publicintlengthOfLongestSubstring(Strings){int[]m=newint[256];Arrays.fill(m,-1);intres=0,left=-1;for(inti=0;i<s.length();++i){left=Math.max(left,m[s.charAt(i)]);m[s.charAt(i)]=i;res=Math.max(res,i-left);}returnres;}}