LeetCode-438.Find All Anagrams in a String

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and pwill not be larger than 20,100.

The order of output does not matter.

Example 1:

Input:
s: "cbaebabacd" p: "abc"
Output:
[0, 6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

Example 2:

Input:
s: "abab" p: "ab"
Output:
[0, 1, 2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

 

根据滑动窗口的思想,利用map记录count,时间复杂度为O(n)

public List<Integer> findAnagrams(String s, String p) {//map 滑动窗口 mytip
        List<Integer> re = new ArrayList<>();
        if(null==s||null==p||s.length()<p.length()){
            return re;
        }
        Map<Character,Integer> map = new HashMap<>();
        for (int i = 0; i < p.length(); i++) {
            char c= p.charAt(i);
            if(map.containsKey(c)){
                map.put(c,map.get(c)+1);
            }
            else{
                map.put(c,1);
            }
        }
        int left =0;
        int right =0;
        int count = p.length();
        while(right<s.length()){
            char c = s.charAt(right);
            right++;
            if(map.containsKey(c)){
                if(map.get(c)>=1){
                    count--;
                }
                map.put(c,map.get(c)-1);
            }
            if(0==count){
                re.add(left);
            }

            if(right-left==p.length()){
                
                char cl = s.charAt(left);
                left++;
                if(map.containsKey(cl)){
                    if(0<=map.get(cl)){
                        count++;
                    }
                    map.put(cl,map.get(cl)+1);
                   
                }
            }

        }
        return re;
    }

 

相关题

有效的字母异位词 LeetCode242 https://www.cnblogs.com/zhacai/p/10574647.html

异位词分组 LeetCode49 https://www.cnblogs.com/zhacai/p/10576638.html

posted @ 2019-03-25 20:17  月半榨菜  阅读(226)  评论(0编辑  收藏  举报