剑指offer_最长不含重复字符的子字符串
1 import java.util.Arrays; 2 3 public class Solution { 4 5 public int longestSubStringWithoutDuplication(String str) { 6 int curLen=0; 7 int maxLen=0; 8 int [] index =new int[26]; 9 Arrays.fill(index, -1); 10 for (int i = 0; i < str.length(); i++) { 11 int preindex = index[str.charAt(i)-'a']; 12 if(preindex==-1||i-preindex>curLen){ 13 curLen++; 14 } 15 else{ 16 maxLen=Math.max(curLen, maxLen); 17 curLen=i-preindex; 18 } 19 index[str.charAt(i)-'a']=i; 20 } 21 maxLen=Math.max(curLen, maxLen); 22 return maxLen; 23 24 } 25 26 public static void main(String[] args) { 27 Solution s = new Solution(); 28 int longestSubStringWithoutDuplication = s.longestSubStringWithoutDuplication("arabcacf"); 29 System.out.println(longestSubStringWithoutDuplication); 30 } 31 }
1、若第i个字符在之前没出现过,则 f(i) = f(i-1) + 1;
2、若第i个字符在之前出现过,
计算第i个字符距离上次出现之间的距离为d
(a)若d <= f(i-1),则说明第i个字符上次出现在f(i-1)对应的不重复字符串之内,那么这时候更新 f(i) = d
(b)若d > f(i-1),则无影响,f(i) = f(i-1) + 1

浙公网安备 33010602011771号