Home » Is Subsequence – Coding program

Is Subsequence – Coding program

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

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:

  1. Start both string searches from the zeroth index.
  2. While loop with check, t greater than s.
  3. if(s[sLength]==t[tLength]) then only increase count of sLengthand every time increase the count of tLength.
  4. if(sLength==s.Length) then return true or else return by default false.

Need help?

Read this post again, if you have any confusion, or else add your questions in Community

Tags: