leetcode 438. Find All Anagrams in a String

题意:在s串中找到与p串所用字符种类,数目相同的所有子串的起始位置。初始化两个变量start,end,diff。start,end为s串中目前正在与p串比较的子串的起始位置和终止位置。diff为这一子串与p串的差异数。当diff == 0 && (end-start+1) == p.length。则说明我们找到了一个子串,存储start。当diff == 0时,我们需要将start前移,并相应地增加diff。说了很多,当实际上仔细想想就明白了,不难。

class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        
        int slen = s.length(), plen = p.length();
        LinkedList<Integer> ans = new LinkedList<>();
        if(slen < plen) return ans;
        int[] c = new int [26];
        for(int i=0;i<plen;i++)
            c[p.charAt(i)-'a']++;
        
        int diff = plen;
        int start = 0, end = 0;
        while(start<=end && end < slen){
            
            int t = s.charAt(end);
            if(--c[t-'a'] >= 0 ) diff--;
            
            while(diff == 0){
                t = s.charAt(start);
                int temp = end - start+1;
                if(temp == plen) ans.add(start);
                
                if(++c[t-'a'] > 0) diff++;
                start++;
            }
            end++;
        }
        
        return ans;
    }
}

  

猜你喜欢

转载自www.cnblogs.com/ctqchina/p/10111479.html