Permutation in String - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Thursday 13 August 2020

Permutation in String

Permutation in String

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

 

Constraints:

  • The input strings only contain lower case letters.
  • The length of both given strings is in range [1, 10,000].

 

class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        int n=s1.size(),m=s2.size();
        if(n==0||m==0||m<n)return false;
        int a[26]={0},b[26]={0};
        for(int i=0;i<n;++i)
        {
            a[s1[i]-'a']++;
            b[s2[i]-'a']++;
           
        }
        int i=n,j;
        while(i<m)
        {
            for(j=0;j<26;++j)
            {
                if(a[j]!=b[j])
                    break;
            }
            if(j==26)
                return true;
            b[s2[i-n]-'a']--;
            b[s2[i]-'a']++;
            ++i;
        }
           for(j=0;j<26;++j)
            {
                if(a[j]!=b[j])
                    break;
            }
            if(j==26)
                return true;
        return false;
    }
};