1. Question
求最长无重复字符子串。
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.
2. Solution
定义如下三个变量:
- i:指示候选最长子串串首,初值为0。
- j:指示候选最长子串串尾,初值为0。
- sub:代表候选最长子串,初值为第一个字符。
1 for( ; i<=len; ){ 2 for( ; j<=len; j++ ) 3 判断chars[j]是否在sub中{ 4 如果在{ 5 i = sub中chars[j]的位置+1; 6 j++; 7 修改sub; 8 break;
} 9 } 10 }
1 public class Solution { 2 //O(n2) time 3 public int lengthOfLongestSubstring( String s ){ 4 if( s.length() <= 1 ) return s.length(); 5 int len = 0; 6 int from = 0; 7 int end = 1; 8 for( int i=1; i<s.length(); i++ ){ 9 int index = s.substring(from, end).indexOf(s.codePointAt(i)); // O(n) time 10 //the present char can be added to the substring 11 if( index<0 ) 12 end++; 13 //the present char is an duplicate for this substring 14 else{ 15 len = ( end-from > len ) ? (end-from) : len; 16 from += index+1; 17 end++; 18 } 19 } 20 21 len = ( end-from > len ) ? (end-from) : len; 22 23 return len; 24 } 25 }
3. 复杂度分析
外循环遍历字符串,内循环遍历候选子串。时间复杂度O(n2)