Check if a string is a subsequence of another string ( using Stacks ) - GeeksforGeeks

10 Jun, 2021
Given a string S, the task is to check if the string target is a subsequence of string S or not, using a Stack.
Examples:
Input: S = ”KOTTAYAM”, target = ”KOTA”Output: YesExplanation: “KOTA” is a subsequence of “KOTTAYAM”.
Input: S = ”GEEKSFORGEEKS”, target =”FORFOR”Output: No
Approach: Follow the steps to solve the problem:
Initialize a stack s.
Iterate over the characters of the string target.
target pushed into the stack
Traverse the string S in the reverse.
If the current character of string S is same as the character at the top of the stack, pop the top element of the stack.
Traversing in S
Traversing in S
Popping from stack
Traversing in S
Popping from stack
Traversing in st
Popping from stack
Traversing in S
Stack becomes empty
If at any point, the stack becomes empty, it can be concluded that target is a subsequence of S.
Otherwise, target is not a subsequence of S.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program for the above approach #include <bits/stdc++.h>using namespace std; // Function to check if target// is a subsequence of string Svoid checkforSubsequence(string S,                         string target){     // Declare a stack    stack<char> s;     // Push the characters of    // target into the stack    for (int i = 0; i < target.size(); i++) {        s.push(target[i]);    }     // Traverse the string S in reverse    for (int i = (int)S.size() - 1; i >= 0; i--) {         // If the stack is empty        if (s.empty()) {             cout << "Yes" << endl;            return;        }         // if S[i] is same as the        // top of the stack        if (S[i] == s.top()) {             // Pop the top of stack            s.pop();        }    }     // Stack s is empty    if (s.empty())        cout << "Yes" << endl;    else        cout << "No" << endl;} // Driver Codeint main(){    string S = "KOTTAYAM";    string target = "KOTA";     checkforSubsequence(S, target);     return 0;}
// Java approach for the above approachimport java.util.Stack; public class GFG {     // Function to check if target    // is a subsequence of string S    static void checkforSubsequence(String S, String target)    {         // Declare a stack        Stack<Character> s = new Stack<>();         // Push the characters of        // target into the stack        for (int i = 0; i < target.length(); i++) {            s.push(target.charAt(i));        }         // Traverse the string S in reverse        for (int i = (int)S.length() - 1; i >= 0; i--) {             // If the stack is empty            if (s.empty()) {                 System.out.println("Yes");                return;            }             // if S[i] is same as the            // top of the stack            if (S.charAt(i) == s.peek()) {                 // Pop the top of stack                s.pop();            }        }         // Stack s is empty        if (s.empty())            System.out.println("Yes");        else            System.out.println("No");    }     // Driver Code    public static void main(String[] args)    {        String S = "KOTTAYAM";        String target = "KOTA";         checkforSubsequence(S, target);    }} // This code is contributed by abhinavjain194
# Python3 program for the above approach # Function to check if target# is a subsequence of string Sdef checkforSubsequence(S, target):     # Declare a stack    s = []     # Push the characters of    # target into the stack    for i in range(len(target)):        s.append(target[i])     # Traverse the string S in reverse    for i in range(len(S) - 1, -1, -1):         # If the stack is empty        if (len(s) == 0):            print("Yes")            return         # If S[i] is same as the        # top of the stack        if (S[i] == s[-1]):             # Pop the top of stack            s.pop()     # Stack s is empty    if (len(s) == 0):        print("Yes")    else:        print("No") # Driver Codeif __name__ == "__main__":     S = "KOTTAYAM"    target = "KOTA"     checkforSubsequence(S, target)     # This code is contributed by ukasp
// C# approach for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to check if target// is a subsequence of string Sstatic void checkforSubsequence(String S,                                String target){         // Declare a stack    Stack<char> s = new Stack<char>();     // Push the characters of    // target into the stack    for(int i = 0; i < target.Length; i++)    {        s.Push(target[i]);    }     // Traverse the string S in reverse    for(int i = (int)S.Length - 1; i >= 0; i--)    {         // If the stack is empty        if (s.Count == 0)        {            Console.WriteLine("Yes");            return;        }         // If S[i] is same as the        // top of the stack        if (S[i] == s.Peek())        {                         // Pop the top of stack            s.Pop();        }    }     // Stack s is empty    if (s.Count == 0)        Console.WriteLine("Yes");    else        Console.WriteLine("No");} // Driver Codepublic static void Main(String[] args){    String S = "KOTTAYAM";    String target = "KOTA";     checkforSubsequence(S, target);}} // This code is contributed by shikhasingrajput
<script>   // JavaScript Program for the above approach // Function to check if target// is a subsequence of string Sfunction checkforSubsequence(S, target){     // Declare a stack    var s = [];     // Push the characters of    // target into the stack    for (var i = 0; i < target.length; i++) {        s.push(target[i]);    }     // Traverse the string S in reverse    for (var i = S.length - 1; i >= 0; i--) {         // If the stack is empty        if (s.length==0) {             document.write( "Yes");            return;        }         // if S[i] is same as the        // top of the stack        if (S[i] == s[s.length-1]) {             // Pop the top of stack            s.pop();        }    }     // Stack s is empty    if (s.length==0)        document.write( "Yes" );    else        document.write( "No" );} // Driver Code var S = "KOTTAYAM";var target = "KOTA";checkforSubsequence(S, target);  </script>
Yes
 
Time Complexity : O(N) Auxiliary Space : O(N)
 
abhinavjain194
ukasp
shikhasingrajput
rrrtnx
cpp-stack-functions
subsequence
Stack
Strings
Strings
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Real-time application of Data Structures
Reverse individual words
Sort a stack using a temporary stack
Iterative Tower of Hanoi
ZigZag Tree Traversal
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types