码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-438.Find All Anagrams in a String

时间:2019-03-25 20:47:13      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:tps   i++   span   order   nta   key   color   output   分组   

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

LeetCode-438.Find All Anagrams in a String

标签:tps   i++   span   order   nta   key   color   output   分组   

原文地址:https://www.cnblogs.com/zhacai/p/10596274.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!