3. 438 找到字符串中所有字母异位词(mid)

该博客讨论了一种使用滑动窗口算法来解决LeetCode上的438题——找到字符串中所有字母异位词。博主详细解释了代码的逻辑,并通过四个关键点阐述了如何判断和移动窗口,以找出所有匹配的子串。文章强调理解这些关键点是解决问题的关键。
摘要由CSDN通过智能技术生成

一、题目

Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

 

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".
 

Constraints:

1 <= s.length, p.length <= 3 * 104
s and p consist of lowercase English letters.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-anagrams-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、 思路

套模板,debug的地方就四个或者五个,弄明白每个关键点到底应该怎么写就ok了。

二、自己写的

1.代码

第一次写

class Solution {
    public List<Integer> findAnagrams(String s, String p) {

        List<Integer> res = new ArrayList<Integer>();

        HashMap<Character,Integer> need = new HashMap<Character,Integer>();
        HashMap<Character,Integer> window = new HashMap<Character,Integer>();

        int left = 0, right = 0;
        int valid = 0;
        int len = Integer.MAX_VALUE;

        for (char c : p.toCharArray()) {
            need.put(c, need.getOrDefault(c, 0) + 1);
        }

        //第一个debug点,考虑什么时候窗口右移
        while (right < s.length()) {

            char c = s.charAt(right);
            right++;
            len = right - left;

            //第二个debug点,什么时候window和valid“变大”
            if (need.containsKey(c)) {
                window.put(c, window.getOrDefault(c, 0) + 1);
                if (need.get(c).equals(window.get(c)))
                    valid++;
            }

            //第三个debug点,什么时候开始窗口左移
            while (len >= p.length()) {
                //什么情况下满足要求
                if ((len == p.length()) && (valid == need.size()))
                    res.add(left);

                char d = s.charAt(left);
                left++;
                len = right - left;
                
                //第四个debug点,什么时候window和valid“变小”
                if (need.containsKey(d)) {
                    if (need.get(d).equals(window.get(d)))
                        valid--;
                    window.put(d, window.get(d) - 1);
                }
            }
        }
        return res;
    }
}

//正确,弄清楚那几个点的逻辑就ok。

三、标准答案

1.方法一(滑动窗口)

class Solution {
    public List<Integer> findAnagrams(String s, String p) {

        List<Integer> res = new ArrayList<Integer>();

        HashMap<Character,Integer> need = new HashMap<Character,Integer>();
        HashMap<Character,Integer> window = new HashMap<Character,Integer>();

        int left = 0, right = 0;
        int valid = 0;
        int len = Integer.MAX_VALUE;

        for (char c : p.toCharArray()) {
            need.put(c, need.getOrDefault(c, 0) + 1);
        }

        //第一个debug点,考虑什么时候窗口右移
        while (right < s.length()) {

            char c = s.charAt(right);
            right++;
            len = right - left;

            //第二个debug点,什么时候window和valid“变大”
            if (need.containsKey(c)) {
                window.put(c, window.getOrDefault(c, 0) + 1);
                if (need.get(c).equals(window.get(c)))
                    valid++;
            }

            //第三个debug点,什么时候开始窗口左移
            while (len >= p.length()) {
                //什么情况下满足要求
                if ((len == p.length()) && (valid == need.size()))
                    res.add(left);

                char d = s.charAt(left);
                left++;
                len = right - left;
                
                //第四个debug点,什么时候window和valid“变小”
                if (need.containsKey(d)) {
                    if (need.get(d).equals(window.get(d)))
                        valid--;
                    window.put(d, window.get(d) - 1);
                }
            }
        }
        return res;
    }
}

2.总结

弄明白那几个debug点的逻辑就ok了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用滑动窗口和哈希表来解决这个问题。具体步骤如下: 1. 定义一个哈希表,用于记录目标字符串每个字符出现的次数。 2. 定义两个指针 left 和 right,分别表示滑动窗口的左右边界。 3. 初始化 left 和 right 为 0,表示滑动窗口的大小为 0。 4. 遍历目标字符串,每次将 right 指针向右移动一格,并将对应的字符出现次数加一。 5. 如果 right - left == p.length(),说明滑动窗口的大小已经达到了目标字符串 p 的长度,此时需要判断滑动窗口的字符是否是 p 的一个字母异位。 6. 判断方法是比较滑动窗口的字符出现次数和 p 每个字符出现次数是否一致,如果一致则说明找到了一个字母异位。 7. 将 left 指针向右移动一格,同时将对应的字符出现次数减一,继续遍历目标字符串Java 代码实现如下: ``` public List<Integer> findAnagrams(String s, String p) { List<Integer> result = new ArrayList<>(); if (s == null || s.length() == 0 || p == null || p.length() == 0) { return result; } int[] hash = new int[26]; for (char c : p.toCharArray()) { hash[c - 'a']++; } int left = 0, right = 0, count = p.length(); while (right < s.length()) { if (hash[s.charAt(right) - 'a'] > 0) { count--; } hash[s.charAt(right) - 'a']--; right++; if (count == 0) { result.add(left); } if (right - left == p.length()) { if (hash[s.charAt(left) - 'a'] >= 0) { count++; } hash[s.charAt(left) - 'a']++; left++; } } return result; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值