LeetCode #3 Longest Substring Without Repeating Characters (M)

[Problem]

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.

 

[Analysis]

这题主要是对brute force matching进行优化。在对字符串进行扫描的过程中,使用一个变量start记录此次扫描的起点,使用一个Hash Table记录已出现的字符以及出现的位置。假如在扫描的过程中遇到了已出现的字符,那么判断这次扫描过的子串长度是不是最长,然后进行下一次扫描。关键在于下一次扫描的起点不是start+1而是重复字符上一次出现的位置+1,因为包含它的所有子串都不可能比上一次扫描过的子串长(在不包含重复字符的前提下)。

 

[Solution]

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

 

posted on 2015-09-30 23:05  张惬意  阅读(102)  评论(0编辑  收藏  举报