Exploring the JavaScript Function ‘isSubsequence’ for Efficient String Matching
Understanding the isSubsequence
Function
The isSubsequence
function is a JavaScript function designed to check if a given string s
can be derived from another string t
by deleting some (or no) characters, without changing the relative order of the remaining characters in t
.
function isSubsequence(s, t) {
let p1 = 0;
let l1 = s.length;
for (let i = 0; i < t.length; i++) {
if (s[p1] === t[i]) {
p1++;
}
if (p1 === l1) {
return true;
}
}
return false;
}
How the Function Works
- The function takes two string parameters,
s
andt
. - It initializes two pointers,
p1
andl1
, to 0 and the length ofs
, respectively. - The function then iterates over each character in the target string
t
using afor
loop. - Inside the loop, it checks if the character at position
p1
in the subsequences
matches the current character in the targett
. - If there is a match, it increments the pointer
p1
. - The function also checks if
p1
has reached the length ofs
. If this condition is met, it means that all characters ins
have been found int
in the same order, so it returnstrue
. - If the loop completes without finding all characters of
s
int
, it returnsfalse
.
Example Usage
Let’s see some examples of how the isSubsequence
function can be used:
console.log(isSubsequence('abc', 'ahbgdc')); // Output: true
console.log(isSubsequence('axc', 'ahbgdc')); // Output: false
Conclusion
The isSubsequence
function provides an efficient way to determine if one string can be formed from another by deleting characters while maintaining their relative order. This is a versatile tool that can be used in various applications, such as text processing, bioinformatics, and more. Understanding and utilizing functions like isSubsequence
is essential for every JavaScript developer's toolkit.
Resource: Leetcode 392. Is Subsequence