2014年4月6日 星期日

[LeetCode] Longest Substring Without Repeating Characters

Problems:
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.
Solution: O(n) space+O(n) time


public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s == null || s.length() == 0)
            return 0;
        
        if(s.length() == 1)
            return 1;
            
        char set[] = s.toCharArray();
        
        HashMap map = new HashMap();
        int cur = 0;
        int max = 1;
        map.put(""+set[0], 0);
        for(int i=1; i< set.length;i++){
            String key = ""+set[i]; 
            if(map.get(key) == null){
                map.put(key, i);
            }else{
                int p = map.get(key);
                cur = Math.max(p+1, cur);
                map.put(key,i);
            }
            max = Math.max(max, i-cur+1);
        }
        
        return max;
    }
}
Notice:
1. Because ArrayUtils are not allowed,otherwise we can use Character
Character[] set = ArrayUtils.toObject(s.toCharArray());
2. cur = Math.max(p+1, cur); is very important

沒有留言:

張貼留言