438. Find All Anagrams in a String#3(Done)

Solution#3

public class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> list = new ArrayList<>();
        if (s == null || s.length() == 0 || p == null || p.length() == 0) return list;
        char[] pc = p.toCharArray();
        char[] sc = s.toCharArray();
        int fast = 0, slow = 0;
        int count = pc.length;
        int[] table = new int[26];
        for (char c : pc) {
            table[c - 'a']++;
        }
        while (fast < sc.length) {
            if (--table[sc[fast++] - 'a'] >= 0) {
                count--;
            }
            if (count == 0) {
                list.add(slow);
            }
            if (fast - slow == pc.length && table[sc[slow++] - 'a']++ >= 0) {
                count++;
            }
        }
        return list;
    }
}

Solution#2

Solution#1

public class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        int[] table = new int[26];
        int pLength = p.length();
        for (int i = 0; i < pLength; i++) {
            table[p.charAt(i) - 'a']++;
        }
        int[] tmp = new int[26];
        System.arraycopy(table, 0, tmp, 0, 26);
        int count = 0;
        for (int i = 0; i < s.length() - pLength + 1; i++) {
            if (table[s.charAt(i) - 'a'] > 0) {
                table[s.charAt(i) - 'a']--;
                count++;
                for (int j = 1; j < pLength; j++) {
                    if (--table[s.charAt(i + j) - 'a'] < 0) break;
                    count++;
                }
                if (count == pLength) result.add(i);
                count = 0;
                System.arraycopy(tmp, 0, table, 0, 26);
            }
        }
        return result;
    }
}

Problem#2
* 滑窗法没有掌握

Problem#1
* O(n2) 时间复杂度
* 用滑窗法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值