算法(1)最大不重复子串

2018-09-15  本文已影响0人  来搞事情

LeetCode 算法题,最大不重复子串


问题

使用滑动窗口办法解决:
窗口有两个坐标,start(i)和end(j),起初start=end,end++,判断s[end]是否在s[0]到s[end-1]这里面,如果存在并且下标大于start的话,就将start滑动到相等的那个值下标加一的位置。

static int solution(String str){
        int n = str.length();
        //用hashmap保存key对应的下标,因为start要取下一个值,所以保存的下标加一
        HashMap<Character,Integer> map = new HashMap<>();
        int i = 0, j = 0, ans = 0;
        for (j = 0; j < n; j++){
            if (map.containsKey(str.charAt(j))){
                i = Math.max(i,map.get(str.charAt(j)));
            }
            //插入新值或者将旧值更新成新值
            map.put(str.charAt(j), j + 1);
            ans = Math.max(ans, j - i + 1);
        }
        return ans;
    }

还有一种滑动窗口,使用HashSet保存查询过的值,当出现重复值的时候,移除start处元素,然后start+1,相当于窗口向前滑动一位。

static int solution(String str){
        int i = 0, j = 0,ans = 0;
        int n = str.length();
        HashSet set = new HashSet<>();
        while(i < n && j < n){
            if(set.contains(str.charAt(j))){
                set.remove(str.charAt(i++));
            }else{
                set.add(str.charAt(j++));
                ans = Math.max(ans,j - i);
            }
        }
        return ans;
    }
上一篇 下一篇

猜你喜欢

热点阅读