Thursday, February 18, 2016

[LeetCode] 3. Longest Substring Without Repeating Characters

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.

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int len = s.length();
        if(0 == len)
            return 0;
        
        int l = 0;

        int resLen = -1;
        HashMap m = new HashMap();
        
        for(int i = 0; i < len; ++i){
            if(m.containsKey(s.charAt(i))){
                int lnew = m.get(s.charAt(i))+1;
                while(l < lnew){
                    m.remove(s.charAt(l++));
                }
                
            }
            m.put(s.charAt(i), i);
            resLen = Math.max(resLen, i - l +1);
        }
        
        return resLen;
    }
}

No comments:

Post a Comment