Longest Substring Without Repeating Characters
Source
Given a string, find the length of the longest substring
repeating characters.
Example
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.
Challenge
O(n) time
Java
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length()==0) return 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int max=0;
for (int end=0, start=0; end<s.length(); ++end){
if (map.containsKey(s.charAt(end))){
start = Math.max(start, map.get(s.charAt(end))+1);
}
map.put(s.charAt(end), end);
max = Math.max(max, end-start+1);
}
return max;
}
}