Question 11 of 75 - LeetCode Weekly Challenge

LeetCode Challenge #392. Is Subsequence

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 "abcde" while "aec" is not).

 

Example 1:

Input: s = "abc", t = "ahbgdc"
Output: true

Example 2:

Input: s = "axc", t = "ahbgdc"
Output: false

 

Constraints:

  • 0 <= s.length <= 100
  • 0 <= t.length <= 104
  • s and t consist only of lowercase English letters.
Video Solution
C++ Solution
				
					class Solution {
public:
bool isSubsequence(string s, string t) {
        if(s.length()==0)
            return true;
        else if(t.length()<s.length())
            return false;

        int j=0;

        for(int i=0; i<=t.length(); i++)
        {
            cout<<s[j];
            if(s[j]==t[i])
                j++;
            if(j==s.length())
                return true;
        }
        return false;
    }
}
				
			
Code Explanation

This function aims to determine whether a given string ‘s’ is a subsequent of another string ‘t’.

A subsequence is a sequence of characters that appears in the same order as they appear in another longer sequence, with the possibility of skipping characters. 

Let’s have a look at the detailed explanation of the code:

  1. As we know, an empty string is the subsequence of every string, so let us check its length first, if 

( s . length()==0 ) 

  • Which is true, so return true in this case.

Else if 

  • If the length of the subsequence string is more than the length of the main string, then it returns False; because that cannot be true. We are very sure about these conditions here. Now let’s see the other steps. 
  1. Now we initialize an integer variable ‘j’ to 0. Which will iterate through the characters of string ‘s’. 
  1. Then we used a for loop with variable ‘i’ that will iterate upon the length of strings for checking each alphabet. 
  • inside the loop it checks, if the current character of ‘s’[ j ] is equal to ‘s’[ i ] if it is, then increment ‘j’ further. 
  • But if the ‘i’ ends then the string will also come to an end so, before the ending of ‘i’ we’ll check if ‘j’ has reached to the last element of the string and if it does so, return ‘True’. 
  1. If the loop continues without returning ‘true’, or it doesn’t find all the letters in order,  it means ‘s’ is not a subsequence of ‘t’, and the function returns ‘false’ in this case.

Happy Coding with edSlash