Longest Substring Without Repeating Characters
May 16 '11
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) { HashSet<Character> set = new HashSet<Character>(); int max =0; int candidateStartIndex =0; for (int index =0;index <s.length();index++){ char c = s.charAt(index); if (set.contains(c)){ max = Math.max(max, index-candidateStartIndex); while(s.charAt(index)!=s.charAt(candidateStartIndex)){ set.remove(s.charAt(candidateStartIndex));//remove duplicated one candidateStartIndex++; } candidateStartIndex++; }else{ set.add(c); } } max = Math.max(max, s.length()-candidateStartIndex); //check from the first return max; } }
learned: remove dup from beginning of the string, then check from last point if the last part is non dup