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

Approach

Java


public class PermutationInString {
    public static void main(String[] args) {
        String s1 = "ab";
        String s2 = "eidbaooo";
        System.out.println(checkInclusion(s1, s2));
    }

    static boolean checkInclusion(String pString s) {
        int n = s.length();
        int m = p.length();
        if (n < m)
            return false;
        
        int f[] = new int[26];
        int f1[] = new int[26];
        int flag = 0;
        for (int i = 0; i < m; i++)
            f[s.charAt(i) - 'a']++;
        for (int i = 0; i < m; i++)
            f1[p.charAt(i) - 'a']++;
        for (int i = 0; i < 26; i++)
            if (f[i] != f1[i]) {
                flag = 1;
                break;
            }
        if (flag == 0)
            return true;
        for (int i = m; i < n; i++) {
            flag = 0;
            f[s.charAt(i) - 'a']++;
            f[s.charAt(i - m) - 'a']--;
            for (int j = 0; j < 26; j++) {
                if (f[j] != f1[j]) {
                    flag = 1;
                    break;
                }
            }
            if (flag == 0)
                return true;
        }
        return false;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

bool checkInclusion(string pstring s
{
       int n=s.size(),m=p.size();
        if(n<m)
              return false;
       
        int f[26]={0},f1[26]={0},flag=0;
        for(int i=0;i<m;i++)
              f[s[i]-'a']++;
        for(int i=0;i<m;i++)
               f1[p[i]-'a']++;
        for(int i=0;i<26;i++)
               if(f[i]!=f1[i])
               {
                     flag=1;
                     break;
               }
       if(flag==0)
              return true;
        for(int i=m;i<n;i++)
         {      
             flag=0;
             f[s[i]-'a']++;
             f[s[i-m]-'a']--;
             for(int i=0;i<26;i++)
             {
                 if(f[i]!=f1[i])
                 {
                     flag=1;
                     break;
                 }
             }
          if(flag==0)
                 return true;
         }
     return false;
}
int main()
{
    string s1 = "ab" ,s2 = "eidbaooo";
    if(checkInclusion(s1,s2))
       cout<<"true";
    else
      cout<<"false";
      return 0;
}


No comments:

Post a Comment