Friday, May 5, 2017

3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.



Solution:

We keep two pointers i and j and a HashMap to keep track of substring.

The HashMap maintains a character to index map.

We set i to be the start of a substring and j to be the end.

For each j, we check if the character is in the substring by checking the HashMap.

If it has not appeared before, we simply add j + 1 (the next position to this character) to the HashMap. This indicates that if we found a repeat at some point, we need to set i (start of the substring) to skip this character to its next position.

If there is a repeat, we set i to skip the repeated character.



Code:


public class Solution {
    public int lengthOfLongestSubstring(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        int max = 0;
        for (int i = 0, j = 0; j < s.length(); j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(i, map.get(s.charAt(j)));
            }
            max = Math.max(max, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return max;
    }
}




public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int[] check = new int[256];
        int max = 0;
        for (int i = 0, j = 0; j < s.length(); j++) {
            i = Math.max(i, check[s.charAt(j)]);
            max = Math.max(max, j - i + 1);
            check[s.charAt(j)] = j + 1;
        }
        return max;
    }
}




public class Solution {
    public int lengthOfLongestSubstring(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        int start = 0;
        int end = 0;
        int max = 0;
        int count = 0;
        while (end < s.length()) {
            char c = s.charAt(end);
            if (!map.containsKey(c)) {
                map.put(c, 1);
            }
            else {
                map.put(c, map.get(c) + 1);
            }
            if (map.get(c) > 1) {
                count++;
            }
            end++;
            while (count > 0) {
                char ch = s.charAt(start);
                if (map.containsKey(ch)) {
                    map.put(ch, map.get(ch) - 1);
                    if (map.get(ch) > 0) {
                        count--;
                    }
                }
                start++;
            }
            max = Math.max(max, end - start);
        }
        return max;
    }
}