Skip to content

Commit c9dc995

Browse files
committed
Added Is_Subsequence.cpp file
1 parent 142d7cd commit c9dc995

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/* Problem Statement
2+
Given a string s and a string t, check if s is subsequence of t.
3+
A subsequence of a string is a new string which is formed from the original string by deleting some(can be none) of the characters without disturbing the relative positions of the remaining characters.
4+
(ie, "ace" is a subsequence of "abcde" while "aec" is not).
5+
*/
6+
#include<bits/stdc++.h>
7+
using namespace std;
8+
bool isSubsequence(string s, string t) {
9+
int i, j = 0;
10+
if (s.length() == 0) // empty string is always a subsequence
11+
return true;
12+
char c = s[0]; //c stores first character of s
13+
if (t.length() < s.length()) // a string s containing less characters than t cannot be its subsequence
14+
return false;
15+
for (i = 0; i < t.length(); i++)
16+
{
17+
if (t[i] == c)
18+
{
19+
j++; //it moves the iterator to the next character of s
20+
if (j == s.length()) //if the iterator has reached the limit of s , it means it is present as subsequence
21+
return true;
22+
c = s[j];
23+
}
24+
}
25+
return false; //if the conditions are not satisified above, then s is not a subsequence of t
26+
}
27+
int main()
28+
{
29+
string s, t;
30+
cin >> s >> t;
31+
cout << boolalpha; //to display true for 1 and false for 0
32+
cout << isSubsequence(s, t);
33+
return 0;
34+
}

0 commit comments

Comments
 (0)