Leetcode-Longest Substring Without Repeating Characters(Java)

Question:

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.

Thinking:

The basic idea is to maintain a hashmap to keep the exsiting characters. If there is a character appered in the hashmap, then move the index to the last position it emerged. Hold two pointers: one is to record the substring’s start position and the other is to record the substring’s end position. And the pointers can only move forward.

Solution:

public int lengthOfLongestSubstring(String s) {
    HashMap<Character, Integer> alphabeta = new HashMap<Character, Integer>();
    int max = 0;
    int count = 0;
    int idx = 0;

    while (idx+count < s.length()) {

        if (!alphabeta.containsKey(s.charAt(idx + count))) {
            alphabeta.put(s.charAt(idx + count), idx+count);
            count++;
        }
        else {
            idx = alphabeta.get(s.charAt(idx + count)) + 1;
            alphabeta = new HashMap<Character, Integer>();
            count = 0;
        }
        max = Math.max(max, count);
    }

    return max;
}