Friday, January 31, 2014

Longest SubString Without Repeating Characters LeetCode

开始我用的int [] 来存index,发现不行,因为我不知道具体里面有多少个字符。看了下大牛答案,用的是Hashmap非常好用啊。 要想写的快,方法得对。

public int lengthOfLongestSubstring(String s) {
        if (s==null || s.length() == 0) return 0;
     
        Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
        int start = 0;
        int end = 0;
        int len = s.length();
        int result = 0;
     
        while (end < len) {
            Integer c = new Integer(s.charAt(end));
            if (!hm.containsKey(c)){
                hm.put(c, end);
            } else {
                int diff = end - start;
                if (diff > result) result = diff;
                Integer index = hm.get(c);
                start = Math.max(start, index + 1);
                hm.put(c,end);
            }
            end++;
        }
        return (result > (end - start)) ? result : (end - start);
    }

Wow. I was on the right track. For two passes solution, using a boolean array.

public int lengthOfLongestSubstring(String s) {
        boolean[] exist = new boolean [256];
        int i=0, maxLen = 0;
        for (int j=0; j<s.length(); j++) {
            while (exist[s.charAt(j)]) {
                exist[s.charAt(i)] = false;
                i++;
            }
            exist[s.charAt(j)] = true;
            maxLen = Math.max(j-i+1, maxLen);
        }
        return maxLen;
    }

For one pass solution, using a integer array.

No comments:

Post a Comment