题目
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.
思路
该问题可在
O(n)
时间内解决
通过维护两个指针i和j,保证区间[i,j]内没有重复的字符,指针j开始向右移动,使用hashtable记录已访问的字符及其下标,假如当前字符前面已经出现,在hashtable中找到其下标dex,区间max(i,dex)~j将构成新的没有重复字符的子串,最后更新hashtable中该字符的下标
代码
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int lengthOfLongestSubstring(String s) {
int[] map = new int[256];
for(int i=0; i<256; i++) map[i] = -1;
int max = 0;
for(int i=0, j=0; i<s.length(); i++){
char c = s.charAt(i);
j = j > map[c]+1 ? j : map[c]+1;
map[c] = i;
max = max > i-j+1 ? max : i-j+1;
}
return max;
}
}