Regexp solution - JS & PYTHON


  • 0
    N

    JavaScript

    /**
     * @param {string[]} dict
     * @param {string} sentence
     * @return {string}
     */
    const replaceWords = function (dict, sentence) {
      let rep = ' ', n = 1, reg = dict.map(word => sentence.includes(word) && (rep += `$${n++}`, `\\s(${word})\\w+`)).join('|');
      return reg ? (` ${sentence}`).replace(new RegExp(reg, 'g'), rep).substr(1) : sentence;
    };
    

    TEST

    replaceWords(["cat", "bat", "rat"], "the cattle was rattled by the battery")
    

    Python3

    import re
    class Solution:
        def replaceWords(self, dict, sentence):
            """
            :type dict: List[str]
            :type sentence: str
            :rtype: str
            """
            self.rep, self.n = ' ', 1
            def find(word):
                if word in sentence:
                    self.n, self.rep = self.n + 1, self.rep + r'\%d' % self.n
                    return True
            reg = r'|'.join([r'\s(%s)\w+' % word for word in dict if find(word)])
            return re.sub(reg, self.rep, r' ' + sentence)[1:] if reg else sentence
    

Log in to reply
 

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