mardi 7 septembre 2021

Javascript if statement with strict equality operator question

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)); 

Aucun commentaire:

Enregistrer un commentaire