leetcode——567. 字符串的排列

Map<Character,Integer> ori = new HashMap<>();
    public boolean checkInclusion(String s1, String s2) {
        char[] c = s1.toCharArray();
        for(char c1:c){
            ori.put(c1,ori.getOrDefault(c1,0)+1);
        }
        int i = 0;
        int len1 = s1.length();
        int len2 = s2.length();
        while(i<=len2-len1){
            if(ori.containsKey(s2.charAt(i))){
                int j = i;
                Map<Character,Integer> cnt = new HashMap<>();
                boolean flag = false;
                for(;j<i+len1;j++){
                    if(!ori.containsKey(s2.charAt(j))){
                        flag = true;
                        i = j-1;
                        break;
                    }
                    cnt.put(s2.charAt(j),cnt.getOrDefault(s2.charAt(j),0)+1);
                }
                if(!flag) {
                    if(check(cnt)){
                        return true;
                    }
                }
            }
            i++;
        }
        return false;
    }

    private boolean check(Map<Character,Integer> cnt) {
        for (char c : ori.keySet()) {
            if (!cnt.getOrDefault(c, 0).equals(ori.get(c))) {
                return false;
            }
        }
        return true;
    }

 

 对是对了,但是好慢。

public boolean checkInclusion(String s1, String s2) {
        Map<Character,Integer> need = new HashMap<>();
        Map<Character,Integer> window = new HashMap<>();
        char[] c = s1.toCharArray();
        for(char c1:c){
            need.put(c1,need.getOrDefault(c1,0)+1);
        }
        int left = 0,right = 0;
        int valid = 0;
        while(right<s2.length()){
            char c1 = s2.charAt(right);
            right++;
            if(need.containsKey(c1)){
                window.put(c1,window.getOrDefault(c1,0)+1);
                if(window.get(c1).equals(need.get(c1))){
                    valid++;
                }
            }
            while (right-left>=s1.length()){
                if(valid == need.size()){
                    return true;
                }
                char d = s2.charAt(left);
                left++;
                if(need.containsKey(d)){
                    if(window.get(d).equals(need.get(d))){
                        valid--;
                    }
                    window.put(d,window.get(d)-1);
                }
            }
        }
        return false;
    }

 

posted @ 2020-09-01 10:22  欣姐姐  阅读(180)  评论(0编辑  收藏  举报