Dynamic Programming: Is second string subsequence of first JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are given two strings str1 and str2, we are required to write a function that checks if str1 is a subsequence of str2.

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.

For example, "ace" is a subsequence of "abcde" while "aec" is not

Example

const str1 = 'ace';
const str2 = 'abcde';
const isSubsequence = (str1, str2) => {
   let i=0;
   let j=0;
   while(i<str1.length){
      if(j===str2.length){
         return false;
      }
      if(str1[i]===str2[j]){
         i++;
      }
      j++;
   };
   return true;
};
console.log(isSubsequence(str1, str2));

Output

And the output in the console will be −

true
raja
Published on 21-Nov-2020 06:20:35
Advertisements