Say you have two strings: exp->aaccbb comp-> aa2bb
This example will return true as there are 2 chars between aa and bb. I have written this code snippet and am wondering if there is a better way do solve this problem and if I am missing any edge cases.
Also, what would be the fastest way to solve this problem with respect to time/place complexity? The solution is a 2 pointer approach with linear complexity. Follow up -> either side can have compressions or both at the same time.
const isNumber = (ch)=>{
return Number(ch) == ch
}
const isExp = (exp, comp)=>{
let i=j=0;
while(i<exp.length && j<comp.length){
if(comp[j] !== exp[i] && !isNumber(comp[j])){
return false
}
else if(isNumber(comp[j])){
let currentCompIdx = j;
/*Find consexutive numbers*/
while(isNumber(comp[currentCompIdx+1]))currentCompIdx++;
/*Get Number from the compressed string*/
const moveIndexBy = Number(comp.slice(j,currentCompIdx+1));
/*set j pointer to index after the number*/
j=currentCompIdx+1;
/*Check if the letters after number is same*/
if(comp[j] !== exp[i+moveIndexBy]){
return false
}
i++;
j++;
}
else{
i++;
j++;
}
}
return true
}
/*Returns true as it has 2 chars between aa and cc*/
alert(isExp("aaccbb", "aa2bb"))
/*Returns true as it has 2 chars between aa and cc and 4 chars between bb and cc*/
alert(isExp("aaccbbqqqqcc", "aa2bb4cc"))
/*Returns true as it has 10 chars between aa and cc */
alert(isExp("aaccbbqqqqsacc", "aa10cc"))
/*Returns false as the exp string as only 1 char between aa and bb */
alert(isExp("aacbb", "aa2bb"))
```