Reputation: 187
I am trying to analyze this solution for the leetcode problem "392. Is Subsequence" as proposed by Mr. raunak1508. I was confused behind the meaning of the first if statement. if(j===t.length)
. I believe that part of the code determines when to return false or to proceed to the next if statement if(s[i]===t[j])
.
Can someone advise if what I'm thinking is correct?
I think the context behind if(j===t.length)
means that if the var j
contains all specific values of var t
which is "ahbgdc" it then returns false....
...But if the second if statement if(s[i]===t[j])
gets completed first by producing a match it returns true. In this case the first if statement if(j===t.length)
does not even have a chance to return false.
//"abz" will return false
let s="abz"
let t="ahbgdc"
function isSubsequence(s, t) {
let i=0;
let j=0;
while(i<s.length){
if(j===t.length){
console.log("t.length is " + t.length)
return false;
}
if(s[i]===t[j]){
i++;
}
j++;
console.log("j is "+ j);
}
return true;
}
console.log(isSubsequence(s, t));
let s="abc"
let t="ahbgdc"
function isSubsequence(s, t) {
let i=0;
let j=0;
while(i<s.length){
if(j===t.length){
return false;
}
if(s[i]===t[j]){
i++;
}
j++;
console.log("j is "+ j);
console.log("t.length is " + t.length)
}
return true;
}
console.log(isSubsequence(s, t));
Upvotes: 0
Views: 375
Reputation: 2270
Here j
is just the currentIndex of t
, since we are moving ahead in t
, while i
do the same for s
let s="abz"
let t="ahbgdc"
initially i = 0
and j = 0
means they both are point to fist character index of s and t respectfully.
the condition for true is reaching i === 2
by i < s.length
before reaching j === 7
by j === t.length
.
This simply means that we should reach final character of s
before we cross beyond t
final character, since t[7]
is undefined
and outside t
string so there is no hope for a true hence we return false;
Upvotes: 1