
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a String is Subsequence of Another 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
#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
Advertisements