Leetcode 567 Permutation in String (滑动窗口经典题)

文章介绍了如何通过滑动窗口算法判断给定的两个字符串s1和s2,s2是否包含s1的一个排列。通过维护两个字符计数数组,检查s2中的字符是否能形成s1的排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Permutation in String
    Medium
    Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
    In other words, return true if one of s1’s permutations is the substring of s2.

Example 1:

Input: s1 = “ab”, s2 = “eidbaooo”
Output: true
Explanation: s2 contains one permutation of s1 (“ba”).
Example 2:

Input: s1 = “ab”, s2 = “eidboaoo”
Output: false

Constraints:

1 <= s1.length, s2.length <= 104
s1 and s2 consist of lowercase English letters.

解法1:滑动窗口。

class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        int len1 = s1.size(), len2 = s2.size();
        vector<int> need(26, 0), actual(26, 0);
        int needCount = 0;
        for (int i = 0; i < len1; i++) {
            if (need[s1[i] - 'a'] == 0) needCount++;
            need[s1[i] - 'a']++;
        }
        int p1 = 0, p2 = 0;
        int validCount = 0;
        while (p2 < len2) {
            char c = s2[p2];

            if (need[c - 'a'] > 0) {
                actual[c - 'a']++;
                if (actual[c - 'a'] == need[c - 'a']) validCount++;
            }
            p2++;
            while (validCount == needCount) {
                int len = p2 - p1;
                if (len == len1) return true;
                if (len > len1) { //move left pointer
                    c = s2[p1];
                    if (need[c - 'a'] > 0) {
                        if (actual[c - 'a'] == need[c - 'a']) {
                            validCount--;
                        }
                        actual[c - 'a']--;
                    }
                    p1++;
                }
            }
        }

        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值