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

第一個(gè)字符串排列之一是第二個(gè)字符串的子串,這個(gè)用哈希表,統(tǒng)計(jì)s1字符串里頭每個(gè)字符出現(xiàn)的次數(shù)。在s2里進(jìn)行滑動(dòng)比較。兩個(gè)vector一樣就可以出就可以出結(jié)果。
代碼如下。

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; 
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容