Problem

Given a string, find the length of the longest substring without 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.

Note

Solution

1. 哈希表法

HashMap Method I

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

HashMap Method II

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

2. 双指针法

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int start = 0, end = 0, count = 0;
        boolean[] mark = new boolean[256];
        while (end < s.length()) {
            if (!mark[s.charAt(end)]) {
                mark[s.charAt(end)] = true;
                count = Math.max(count, end-start+1);
                end++;
            }
            else {
                while (mark[s.charAt(end)]) {
                    mark[s.charAt(start)] = false;
                    start++;
                }
                
                //只有当s.charAt(start) == s.charAt(end)
                //也就是mark[s.charAt(end)] == false时
                //上面的循环才会结束,start++,跳过这个之前的重复字符
                //再将mark[s.charAt(end)]置为true
                
                mark[s.charAt(end)] = true;
                end++;
            }
        }
        return count;
    }
}

linspiration
161 声望53 粉丝