text: Check if a string can be formed from another string using given constraints | C # 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: using System ; using System . Collections . Generic ; class GFG { static bool check ( String S1 , String S2 ) { int n1 = S1 . Length ; int n2 = S2 . Length ; Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n1 ; i ++ ) { if ( mp . ContainsKey ( ( int ) S1 [ i ] ) ) { mp [ ( int ) S1 [ i ] ] = mp [ ( int ) S1 [ i ] ] + 1 ; } else { mp . Add ( ( int ) S1 [ i ] , 1 ) ; } } for ( int i = 0 ; i < n2 ; i ++ ) { if ( mp . ContainsKey ( ( int ) S2 [ i ] ) ) { mp [ ( int ) S2 [ i ] ] = mp [ ( int ) S2 [ i ] ] - 1 ; } else if ( mp . ContainsKey ( S2 [ i ] - 1 ) && mp . ContainsKey ( S2 [ i ] - 2 ) ) { mp [ S2 [ i ] - 1 ] = mp [ S2 [ i ] - 1 ] - 1 ; mp [ S2 [ i ] - 2 ] = mp [ S2 [ i ] - 2 ] - 1 ; } else { return false ; } } return true ; } public static void Main ( String [ ] args ) { String S1 = " abbat " ; String S2 = " cat " ; if ( check ( S1 , S2 ) ) Console . Write ( " YES " ) ; else Console . Write ( " NO " ) ; } }