Simple RegExp Solution


  • 1
    var validWordAbbreviation = function(word, abbr) {
        if (word == null || abbr == null)
            return false;
    
        abbr = abbr.replace(/[1-9]\d*/g, (m) =>
            '.'.repeat(parseInt(m, 10)));
    
        if (word.length !== abbr.length)
            return false;
    
        for (let i = 0; i < abbr.length; i++)
            if (abbr[i] !== '.' && word[i] !== abbr[i])
                return false;
        
        return true;
    };
    

  • 1

    Hmm... you're building a regular expression but then you don't really use it like one. Once you have your changed abbr, you can just do this:

    return new RegExp('^' + abbr + '$').test(word)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.