Monday, July 7, 2014

Leetcode - 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.

[Thoughts]: 这个题有多种解法,因为判断unique char,所以可以假定是ASCII码用数组。 也可以用hashmap计算一次,清空一次。 下面这种做法是严格的O(n), 无重复的走一遍string。
public class Solution {//08
    public int lengthOfLongestSubstring(String s) {
        if(s==null || s.length()==0) return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int pre = -1, res = 0;
        for(int i=0; i<s.length(); i++){
            char k = s.charAt(i);
            if(map.containsKey(k) && map.get(k)>pre){//出现重复char,计算前一段最长距离
                res = Math.max(res, i-pre-1);
                pre = map.get(k);
            }
            map.put(k, i);
        }
        res = Math.max(res, s.length()-pre-1);
        return res;
    }
}

No comments:

Post a Comment