Thursday, September 10, 2015

Longest Substring Without Repeating Characters | Leetcode

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.

---

Solution: Add each character as we see it. Keep the current length of the longest substring ending at current index. If we have a duplicate character, then reduce the length of the current longest substring until there are no more duplicate characters.
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s.isEmpty()) return 0;
        
        int longest = 0;
        int current = 0;
        Set<Character> seen = new HashSet<>();
        
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (seen.contains(c)) {
                while (current > 0) {
                    char d = s.charAt(i - current);
                    seen.remove(d);
                    current--;
                    if (c == d) break;
                }
            }
            seen.add(c);
            current++;
            longest = Math.max(longest, current);
        }
        
        return longest;
    }
}

No comments: