Check if a string is a subsequence of another string ( using Stacks ) | Function to check if target is a subsequence of string S ; Declare a stack ; Push the characters of target into the stack ; Traverse the string S in reverse ; If the stack is empty ; If S [ i ] is same as the top of the stack ; Pop the top of stack ; Stack s is empty ; Driver Code
def checkforSubsequence ( S , target ) : NEW_LINE INDENT s = [ ] NEW_LINE for i in range ( len ( target ) ) : NEW_LINE INDENT s . append ( target [ i ] ) NEW_LINE DEDENT for i in range ( len ( S ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE return NEW_LINE DEDENT if ( S [ i ] == s [ - 1 ] ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT DEDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " KOTTAYAM " NEW_LINE target = " KOTA " NEW_LINE checkforSubsequence ( S , target ) NEW_LINE DEDENT