LeetCode 809. Expressive Words

Description

https://leetcode.com/problems/expressive-words/

Sometimes people repeat letters to represent extra feeling, such as “hello” -> “heeellooo”, “hi” -> “hiiii”.  In these strings like “heeellooo”, we have groups of adjacent letters that are all the same:  “h”, “eee”, “ll”, “ooo”.

For some given string S, a query word is stretchy if it can be made to be equal to S by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is 3 or more.

For example, starting with “hello”, we could do an extension on the group “o” to get “hellooo”, but we cannot get “helloo” since the group “oo” has size less than 3.  Also, we could do another extension like “ll” -> “lllll” to get “helllllooo”.  If S = "helllllooo", then the query word “hello” would be stretchy because of these two extension operations: query = "hello" -> "hellooo" -> "helllllooo" = S.

Given a list of query words, return the number of words that are stretchy. 

Example:
Input: 
S = "heeellooo"
words = ["hello", "hi", "helo"]
Output: 1
Explanation: 
We can extend "e" and "o" in the word "hello" to get "heeellooo".
We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more.

Constraints:

  • 0 <= len(S) <= 100.
  • 0 <= len(words) <= 100.
  • 0 <= len(words[i]) <= 100.
  • S and all words in words consist only of lowercase letters

Explanation

Python Solution

class Solution:
    def expressiveWords(self, S: str, words: List[str]) -> int:
        if not S:
            return 0
        
        s_list = self.count_group(S)
        n = len(s_list)
        
        result = 0
        
        for word in words:
            word_list = self.count_group(word)
            
            if n != len(word_list):
                continue
            
            count = 1
            for i in range(n):
                if not self.can_extend(word_list[i], s_list[i]):
                    count = 0
                    break
            result += count
            
        return result
        
    def count_group(self, s):
        n = len(s)
        count = 1
        result = []
        
        for i in range(1, n):
            if s[i] == s[i - 1]:
                count += 1
            else:
                result.append((s[i - 1], count))
                count = 1
                
        result.append((s[-1], count))
        
        return result

    def can_extend(self, start, end):
        return start[0] == end[0] and \
               (start[1] == end[1] or (start[1] < end[1] and end[1] >= 3))
  • Time Complexity: ~N
  • Space Complexity: ~N

Leave a Reply

Your email address will not be published. Required fields are marked *