text: Check if a string can be formed from another string using given constraints | CPP program to Check if a given string can be formed from another string using given constraints ; Function to check if S2 can be formed of S1 ; length of strings ; hash - table to store count ; store count of each character ; traverse and check for every character ; if the character of s2 is present in s1 ; if the character of s2 is not present in S1 , then check if previous two ASCII characters are present in S1 ; Driver Code ; Calling function to check
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( string S1 , string S2 ) { int n1 = S1 . size ( ) ; int n2 = S2 . size ( ) ; unordered_map < int , int > mp ; for ( int i = 0 ; i < n1 ; i ++ ) { mp [ S1 [ i ] ] ++ ; } for ( int i = 0 ; i < n2 ; i ++ ) { if ( mp [ S2 [ i ] ] ) { mp [ S2 [ i ] ] -- ; } else if ( mp [ S2 [ i ] - 1 ] && mp [ S2 [ i ] - 2 ] ) { mp [ S2 [ i ] - 1 ] -- ; mp [ S2 [ i ] - 2 ] -- ; } else { return false ; } } return true ; } int main ( ) { string S1 = " abbat " ; string S2 = " cat " ; if ( check ( S1 , S2 ) ) cout << " YES " ; else cout << " NO " ; }