package leetCode;
import java.util.Map;
import java.util.HashMap;
public class longestNoRepeating {
public int lengthOfLongestSubstring(String s) {
// Start typing your Java solution below
// DO NOT write main() function
if(s==null||s.length()<1)
return 0;
boolean[] table = new boolean[256];
int max = 1;
int current = 1;
int j = 0;
table[s.charAt(0)] = true;
int i;
for(i = 1 ; i < s.length();i++){
if(table[s.charAt(i)] == true){
current = i - j;
max = Math.max(current,max);
while(s.charAt(j)!=s.charAt(i)){
table[s.charAt(j)] = false;
j++;
}
j++;
}else{
table[s.charAt(i)] = true;
}
}
max = Math.max(i-j,max);
return max;
}
public int longestSubstringWithoutRepeating(String s){
Map<Character,Integer> map = new HashMap<Character,Integer>();
int start = 0;
int end = 0;
int max = 1;
while(end < s.length()){
char cur = s.charAt(end);
if(map.containsKey(cur) && map.get(cur)>= start){
max = Math.max(max, end - start);
start = map.get(cur)+1;
}
map.put(cur, end);
end++;
}
return Math.max(end-start, max);
}
}
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.
A very clever trick is to use HashMap to provide the current eligible character's position.
O(N)
Both are same in logic. But second is more elegant. Also, very import to check the last substring as it may be the longest
Second methods preferred.