Thought:
Try to implement a O(n) method using just one scan of the String.
Use a HashMap to track which letter has occured.
Code:
public class Solution {
public int lengthOfLongestSubstring(String s) {
int max = 0;
int length = 0;
HashMap<Character, Integer> index = new HashMap<Character, Integer>();
for( int i = 0; i < s.length(); i++ ){
char temp = s.charAt(i);
if( !index.containsKey(temp) ){
index.put(temp,i);
length++;
max = Math.max(length, max);
}else{
i = index.get(temp);
index.clear();
length = 0;
}
}
return max;
}
}
No comments:
Post a Comment