一、问题
给定一个字符串,求最大的子字符串(十连续的),并且子字符串中无重复字符。
二、思路
- 每次记录起始值start
- 每次记录遍历过的字符位置ind
- 如果本轮遍历的字符存在的位置大于起始位置,即ind >= start,则更新最大的子字符长度
三、Code
1 package algorithm; 2 3 import java.util.Arrays; 4 5 /** 6 * Created by adrian.wu on 2019/2/25. 7 */ 8 public class LongestSubstring { 9 public int longestSubstring(String s) { 10 int n = s.length(), start = 0, res = 1; 11 if (n == 0) return 0; 12 int[] array = new int[128]; 13 array[s.charAt(0)] = 0; 14 Arrays.fill(array, -1); 15 16 17 for (int i = 1; i < n; i++) { 18 char ch = s.charAt(i); 19 int ind = array[ch]; 20 if (ind >= start) { 21 res = Math.max(res, i - start); 22 start = i + 1; 23 } 24 array[ch] = i; 25 } 26 27 return res; 28 } 29 }