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.
public class Solution {
public int lengthOfLongestSubstring(String s) {
// Start typing your Java solution below
// DO NOT write main() function
if(s == null)
return -1;
int sLen = s.length();
int maxSubLen = 0;
int curSubLen = 0;
int [] exist = new int [256];
for(int j=0; j<256; j++)
exist[j] = -1;
int start =0;
int i = start;
while(i<sLen){
// found repeat char
if(exist[s.charAt(i)] != -1){
maxSubLen = maxSubLen>=curSubLen?maxSubLen:curSubLen;
curSubLen = 0;
start = exist[s.charAt(i)]+1;
i = start;
// clear exist
for(int j=0; j<256; j++)
exist[j] = -1;
}
else{
exist[s.charAt(i)] = i;
i++;
curSubLen++;
}
}
maxSubLen = maxSubLen>=curSubLen?maxSubLen:curSubLen;
return maxSubLen;
}
}
Bugs encountered:
1. Forgot to initialize exist[] to -1;
****************************************Potential Improvement*********************************************
Don't need to change the exist[] everytime. Just move the start index and compare if the value of exist is less than the start index( currently not selected).
By doing this we can keep going forward without fall back to start+1;
------------------------------------------------------------------------------------------------------------------------------------------
LL's solution:
two pointer + HashMap -> O(n)
public class Solution {
public int lengthOfLongestSubstring(String s) {
// Start typing your Java solution below
// DO NOT write main() function
int l = s.length();
int start = 0, end = 0;
int max = 0, current = 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for(end=0; end<l; end++){
char c = s.charAt(end);
//repeat char between start and end
if(map.containsKey(c) && map.get(c)>=start){
if(current>max)
max = current;
int last = map.get(c);
start = last +1;
current = end-start+1;
map.put(c,end);
}
//non-repeat, len++
else{
map.put(c,end);
current++;
}
}
//compare current substring len and max
if(current>max)
max = current;
return max;
}
}