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.
*Difficulty: Medium, Frequency: Medium
https://leetcode.com/problems/longest-substring-without-repeating-characters/
My Solution
public int lengthOfLongestSubstring(String s) {
int maxLen = 0;
int i = 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for(int j = 0; j < s.length(); j++){
if(map.containsKey(s.charAt(j)) && map.get(s.charAt(j)) >= i ){
i = map.get(s.charAt(j))+1; // max substring for char at j
}
map.put(s.charAt(j), j);
maxLen = Math.max(j - i + 1, maxLen);
}
return maxLen;
}
Hints from the book
后来仔细想了一下,第二种方法的意思是,j 遍历一边string s,i 作为指针,找到离 j 所对应字符一样的在0-j之间距离j最近的字符位置,这之间的字符串就是当前对于j的最大substring,每次j过一个指针就update map里面所对应字符的最新位置。
一开始没想明白为什么第一种方法的runtime complexity是O(N),后来想明白了,不要想 i 是怎么跟着 j 动的,单看 i,即便是一点点找i和j之间离j最近的相同字符,i其实只是一个人默默最多陪j走一趟N,一直往前看不会回头,所以runtime是2N所以也就是N了。写下想法默默觉得有点人生哲学的赶脚。。。