滑动窗口:找到字符串中所有字母异位词

题目:
给定两个字符串 s 和 p,找到 s 中所有 p 的 异位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。
异位词 指由相同字母重排列形成的字符串(包括相同的字符串)。

示例 1:

输入: s = “cbaebabacd”, p = “abc”
输出: [0,6]
解释:
起始索引等于 0 的子串是 “cba”, 它是 “abc” 的异位词。
起始索引等于 6 的子串是 “bac”, 它是 “abc” 的异位词。
示例 2:

输入: s = “abab”, p = “ab”
输出: [0,1,2]
解释:
起始索引等于 0 的子串是 “ab”, 它是 “ab” 的异位词。
起始索引等于 1 的子串是 “ba”, 它是 “ab” 的异位词。
起始索引等于 2 的子串是 “ab”, 它是 “ab” 的异位词。

暴力算法

package bishi.mt.leetcode;

import java.util.ArrayList;
import java.util.List;

public class Q438 {
    public List<Integer> findAnagrams(String s, String p) {
        int[] res = new int[26];
        for (int i = 0; i < p.length(); i++) {
            res[p.charAt(i) - 'a']++;
        }
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i <= s.length() - p.length(); i++) {
            if(pan(s.substring(i,i + p.length()),res)){
                result.add(i);
            }
        }
        return result;
    }
    private static boolean pan(String s , int[] res)
    {
        int[] res1 = new int[26];
        for (int i = 0; i < s.length(); i++) {
            res1[s.charAt(i) - 'a']++;
            if(res1[s.charAt(i) - 'a'] > res[s.charAt(i) - 'a'])
                return false;
        }
        for (int i = 0; i < 26; i++) {
            if(res1[s.charAt(i) - 'a'] == res[s.charAt(i) - 'a'])
                return false;
        }
        return true;
    }
}

能过,但效率显然不够,在计算串的时候没有复用前面的结果。

所以可以使用滑动窗口的思路,毕竟每次只增加一个头减少一个尾部。

package bishi.mt.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Q4381 {
    public List<Integer> findAnagrams(String s, String p) {
        int ns = s.length();
        int np = p.length();
        if(ns < np)
            return new ArrayList<>();
        int[] s_res = new int[26];
        int[] p_res = new int[26];
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < np; i++) {
            p_res[p.charAt(i) - 'a']++;
            s_res[s.charAt(i) - 'a']++;
        }
        if(Arrays.equals(s_res,p_res))
            result.add(0);
        int start = 0;
        int end = np;
        while (end < ns)
        {
            s_res[s.charAt(end)-'a']++;
            s_res[s.charAt(start)-'a']--;
            start++;
            end++;
            if(Arrays.equals(s_res,p_res))
                result.add(start);

        }


        return result;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大鱼qss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值