Leetcode #408 Valid Word Abbreviation

Leetcode #408 Valid Word Abbreviation

Difficulty: Easy

This question is not too difficult, but be careful to consider a lot of edge cases.

Thought process:

  • Loop through abbr
  • If the character is a numeric value, keep track of the number (it can be 2 digits), also make sure that it is not a '0' value since it is invalid if it's a leading 0 numeric value.
  • Increase the count/pointer as you iterate. And for each character that is not a numeric value, check it against word.
    • If the character at some point is not matching, you can return immediately.
  • If towards the end, the abbr count (total length of abbr) is the same as word, they match.

Time Complexity: O(n)

Link: Valid Word Abbreviation

/**
 * @param {string} word
 * @param {string} abbr
 * @return {boolean}
 */
var validWordAbbreviation = function(word, abbr) {
    let aCount = 0;
    let int = "";

    for(let i =0;i<abbr.length;i++){
        if(parseInt(int) == 0){
            return false;
        }

        if(!isNaN(abbr[i]) && parseInt(int) != 0){
            int += abbr[i];
        }else{
            if(int.length > 0){
                aCount += parseInt(int);
                int = "";
            }
            ++aCount;
            let idx = aCount -1;
            if(word[idx] != abbr[i]){
                console.log(word[idx]+ " " +  abbr[i]);
                return false;
            }
        }


        if(abbr.length-1 == i) {
            if(int.length > 0){
                aCount += parseInt(int);
                int = "";
            }
        }

    }

    return (aCount == word.length);
};