567. Permutation in String笔记

Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.
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

第一个字符串排列之一是第二个字符串的子串,这个用哈希表,统计s1字符串里头每个字符出现的次数。在s2里进行滑动比较。两个vector一样就可以出就可以出结果。
代码如下。

class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        vector<int> t1(26,0);
        vector<int> t2(26,0);
        int len1 = s1.size();
        int len2 = s2.size();
        if(len1 > len2)
            return false;
        for(int i = 0; i < len1; i++)
        {
            t1[s1[i]-'a']++;
            t2[s2[i]-'a']++;
        }
        if(t1 == t2)
            return true;
        int j = 0;
        for(int i = len1; i<len2; i++)
        {
            t2[s2[j++]-'a']--;
            t2[s2[i]-'a']++;
            if(t1 == t2)
                return true;
        }
        return false; 
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容