Check if a string is a subsequence of another string ( using Stacks ) | Java approach for the above approach ; 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
import java . util . Stack ; public class GFG { static void checkforSubsequence ( String S , String target ) { Stack < Character > s = new Stack < > ( ) ; for ( int i = 0 ; i < target . length ( ) ; i ++ ) { s . push ( target . charAt ( i ) ) ; } for ( int i = ( int ) S . length ( ) - 1 ; i >= 0 ; i -- ) { if ( s . empty ( ) ) { System . out . println ( " Yes " ) ; return ; } if ( S . charAt ( i ) == s . peek ( ) ) { s . pop ( ) ; } } if ( s . empty ( ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } public static void main ( String [ ] args ) { String S = " KOTTAYAM " ; String target = " KOTA " ; checkforSubsequence ( S , target ) ; } }