text: Check if a string can be formed from another string using given constraints | JAVA 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: import java . util . * ; class GFG { static boolean check ( String S1 , String S2 ) { int n1 = S1 . length ( ) ; int n2 = S2 . length ( ) ; HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n1 ; i ++ ) { if ( mp . containsKey ( ( int ) S1 . charAt ( i ) ) ) { mp . put ( ( int ) S1 . charAt ( i ) , mp . get ( ( int ) S1 . charAt ( i ) ) + 1 ) ; } else { mp . put ( ( int ) S1 . charAt ( i ) , 1 ) ; } } for ( int i = 0 ; i < n2 ; i ++ ) { if ( mp . containsKey ( ( int ) S2 . charAt ( i ) ) ) { mp . put ( ( int ) S2 . charAt ( i ) , mp . get ( ( int ) S2 . charAt ( i ) ) - 1 ) ; } else if ( mp . containsKey ( S2 . charAt ( i ) - 1 ) && mp . containsKey ( S2 . charAt ( i ) - 2 ) ) { mp . put ( ( S2 . charAt ( i ) - 1 ) , mp . get ( S2 . charAt ( i ) - 1 ) - 1 ) ; mp . put ( ( S2 . charAt ( i ) - 2 ) , mp . get ( S2 . charAt ( i ) - 2 ) - 1 ) ; } else { return false ; } } return true ; } public static void main ( String [ ] args ) { String S1 = " abbat " ; String S2 = " cat " ; if ( check ( S1 , S2 ) ) System . out . print ( " YES " ) ; else System . out . print ( " NO " ) ; } }