Given two strings s
and t
, return true
if s
is a subsequence of t
, or false
otherwise.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace"
is a subsequence of "<u>a</u>b<u>c</u>d<u>e</u>"
while "aec"
is not).
Example 1:
Input: s = "abc", t = "ahbgdc"
Output: true
Example 2:
Input: s = "axc", t = "ahbgdc"
Output: false
Solution:
public bool IsSubsequence(string s, string t) {
if(s.Length == 0) return true;
int sLength=0,tLength=0;
while(t.Length>tLength){
if(s[sLength]==t[tLength]){
sLength++;
if(sLength==s.Length) return true;
}
tLength++;
}
return false;
}
Here we are trying to search the sequence of string s
in string t
. adding the default case if s length is equal to zero then return true
.
Steps:
- Start both string searches from the zeroth index.
- While loop with check, t greater than s.
- if(s[sLength]==t[tLength]) then only increase count of
sLength
and every time increase the count oftLength
. - if(sLength==s.Length) then return
true
or else return by defaultfalse
.
Need help?
Read this post again, if you have any confusion, or else add your questions in Community