Program to check whether a string is subsequence of other in C++


Suppose we have two strings S and T. We have to check whether S is subsequence of T or not.

So, if the input is like S = "abc", T = "adbrcyxd", then the output will be True

To solve this, we will follow these steps −

  • if s is same as t, then −

    • return true

  • n := size of s, m := size of t

  • j := 0

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • if t[j] is same as s[i], then −

      • (increase j by 1)

    • if j is same as size of t, then −

      • return true

  • return false

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool solve(string t, string s) {
      if(s == t)
      return true;
      int n = s.size();
      int m = t.size();
      int j = 0;
      for(int i = 0; i < n; i++){
         if(t[j] == s[i])
         j++;
         if(j == t.size())
         return true;
      }
      return false;
   }
};
main(){
   Solution ob;
   string S = "abc", T = "adbrcyxd";
   cout << ob.solve(S, T);
}

Input

"abc", "adbrcyxd"

Output

1

Updated on: 21-Oct-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements