1. 程式人生 > >[Leetcode]567. Permutation in String

[Leetcode]567. Permutation in String

最開始的思路是求全排列,然後find一下:

class Solution {
    void swap(char &a, char &b){
        char c=a;
        a=b;
        b=c;
    }
    bool Permutation(string &s){
        if(s.size()==0 ) return false;
        int i;
        for(i = s.size()-2; i >=0; i--){
            if(s[i] < s[i+1]) break;
        }
        if(i == -1) return false;
        int k;
        for(k = s.size()-1; k > i; k--){
            if(s[i] < s[k]) break;
        }
        swap(s[i],s[k]);
        reverse(s.begin()+i+1,s.end());
        return true;
    }
public:
    bool checkInclusion(string s1, string s2) {
        if(s1.size() > s2.size()) return false;
        sort(s1.begin(),s1.end());
        do{
            if(s2.find(s1) != -1)
                return true; 
        }while(Permutation(s1));
        return false;
        
        
    }
};

不出意外的TLE了,看起來還有其它方法,原來是滑動窗:

class Solution {
  
public:
    bool checkInclusion(string s1, string s2) {
        if(s1.size() > s2.size()) return false;
        vector<int> nums1(26,0);
        vector<int> nums2(26,0);
        for(auto x : s1){
            ++nums1[x-'a'];
        }
        for(int i = 0; i < s2.size(); i++){
            ++nums2[s2[i]-'a'];
            if(i >= s1.size()){
                --nums2[s2[i-s1.size()]-'a'];
            }
            if(nums1 == nums2) return true;
        }
        return false;
        
    }
};