Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters
for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.
下面是我的程式(說來慚愧,此處參考了http://www.cnblogs.com/luxiaoxun/archive/2012/10/02/2710471.html)
package com.my.own;
public class Solution5 {
public int lengthOfLongestSubstring(String s) {
if((s==null) || (s.equals(""))){
return 0;
}
if(s.length() == 1){
return 1;
}
int [] next = new int[s.length()];
int[] first = new int[s.length() 1];
first[s.length()] = s.length();
for(int i=s.length() -1; i>=0; i--){
next[i] = s.indexOf(s.charAt(i), i 1)==-1 ? s.length() : s.indexOf(s.charAt(i), i 1);
if(next[i] <first[i 1]){
first[i] = next[i];
}else{
first[i] = first[i 1];
}
}
int maxLen = 0;
for(int i=0; i<s.length(); i ){
if(maxLen <(first[i] -i)){
maxLen = first[i] -i;
}
}
return maxLen;
}
public static void main(String[] args) {
Solution5 s5 = new Solution5();
String s= "bbbbb";
System.out.println(s5.lengthOfLongestSubstring(s));
}
}
写评论
很抱歉,必須登入網站才能發佈留言。