Permutation in String in C++


Suppose we have two strings s1 and s2, we have to write a function to return true if s2 contains the permutation of s1. So we can say that one of the first string's permutations is the substring of the second string. So if the string s1 = “abc”, and second string s2 is “findcab”, then the result will be true, as the permutation of “abc” is true. That is “cab”.

To solve this, we will follow these steps −

  • create two vectors cnt1 and cnt2 of size 26
  • for i in range 0 to s1
    • increase the value of cnt1[s1[i] – ‘a’] by 1
  • j := 0 and required := size of s1
  • for i in range 0 to size of s2
    • x := s2[i]
    • increase cnt2[x – ‘a’] by 1
    • if cnt1[x – ‘a’] and cnt2[x – ‘a’] <= cnt[x – ‘a’], then
      • decrease required by 1
    • while j <= i and cnt2[s2[j] – ‘a’] – 1 >= cnt1[s2[j] – ‘a’], do
      • decrease cnt2[s2[j] – ‘a’] by 1
      • increase j by 1
    • if i – j + 1 = size of s1 and required = 0, then return true
  • return false.

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool checkInclusion(string s1, string s2) {
      vector <int> cnt1(26), cnt2(26);
      for(int i = 0; i < s1.size(); i++)cnt1[s1[i] - 'a']++;
      int j = 0;
      int required = s1.size();
      for(int i = 0; i < s2.size(); i++){
         char x = s2[i];
         cnt2[x - 'a']++;
         if(cnt1[x - 'a'] && cnt2[x - 'a'] <= cnt1[x - 'a']) required--;
         while(j <= i && cnt2[s2[j] - 'a'] - 1 >= cnt1[s2[j] - 'a']){
            cnt2[s2[j] - 'a']--;
            j++;
         }
         if(i - j + 1 == s1.size() && required == 0){
            return true;
         }
      }
      return false;
   }
};
main(){
   Solution ob;
   cout << (ob.checkInclusion("abc", "findcab"));
}

Input

"abc"
"findcab"

Output

1

Updated on: 29-Apr-2020

501 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements