leetcode 438. Find All Anagrams in a String在字符串中寻找同构体(Sliding Window)

问题描述:

  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 p will not be larger than 20,100.

  The order of output does not matter.


这里写图片描述

思路一:简单粗暴,一个个找

代码一:

class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        HashMap<Character, Integer> map = new HashMap<>();
        for(int i = 0; i < p.length(); i++){
            if(map.containsKey(p.charAt(i))){
                int tmp = map.get(p.charAt(i));
                map.replace(p.charAt(i), ++tmp);
            }else
                map.put(p.charAt(i), 1);
        }
        for(int i = 0; i <= s.length() - p.length(); i++){
            HashMap<Character, Integer> tmpMap = new HashMap<>();
            for(int j = i; j < p.length()+i; j++){
                if(!tmpMap.containsKey(s.charAt(j))){
                    tmpMap.put(s.charAt(j), 1);
                }
                else{
                    int tmp = tmpMap.get(s.charAt(j));
                    tmpMap.replace(s.charAt(j), ++tmp);
                }
            }
            if(tmpMap.equals(map))
                result.add(i);            
        }
        return result;
    }
}

  但是:报错!!!Time Limit Exceeded!

这里写图片描述

  去网上搜了一下,发现求子序列的题目一般都用sliding window进行。可以用两个变量left和right代表滑动串口的左右边界,count表示字符串p的大小。首先遍历要寻找的子字符串,将每个字符出现的个数写入数组。然后将左边界和右边界置0,开始进行搜索:

  1. 如果右边界所指字符存在于子字符串中,则count–。即需要的字符串个数减一;
  2. 如果count为0,则正好搜索到所需要的字符串个数,将第一个字符的索引加入结果list中;
  3. 如果此时右边界减左边界为子字符串的长度,此时相当于多一个字符串,所以要删掉左边这个。如果要删掉的这个在字符串中,则需要count加一;如果不在,则count不需要动。

代码:

class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        int[] chars = new int[26];

        if(s == null || p == null || s.length() < p.length())
            return result;
        for(char c : p.toCharArray())
            chars[c - 'a']++;
        int left = 0, right = 0, count = p.length();
        while(right < s.length()){
            if(--chars[s.charAt(right++) - 'a'] >= 0)
                count--;
            if(count == 0)
                result.add(left);
            if(right - left == p.length() && chars[s.charAt(left++) - 'a']++ >= 0)
                count++;
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值