Expressive Words

We need to first identify the groups of consecutive letters in the string s. We also need to identify the count of each group. After that, for each word in the words list, we’ll identify its groups and their counts and compare them with those of s. A word is stretchy if:

  1. Both the word and s have the same groups of consecutive letters.
  2. For each group, if the count in s is 3 or more, the count in the word should be less than or equal to the count in s. If the count in s is less than 3, the count in the word should be the same as the count in s.

Here’s the step-by-step solution:

  1. Write a helper function getGroups that, given a string, returns the groups of consecutive letters and their counts.
  2. Use the helper function to get the groups and counts of s.
  3. For each word in the words list, use the helper function to get its groups and counts. Then, compare them with the groups and counts of s to determine if the word is stretchy.
  4. Return the total count of stretchy words.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution:
    def expressiveWords(self, s: str, words: List[str]) -> int:
        # Helper function to get groups of consecutive letters and their counts
        def getGroups(string):
            groups = []
            counts = []
            i = 0
            while i < len(string):
                char = string[i]
                count = 0
                while i < len(string) and string[i] == char:
                    i += 1
                    count += 1
                groups.append(char)
                counts.append(count)
            return groups, counts

        s_groups, s_counts = getGroups(s)

        # Check if a word is stretchy
        def isStretchy(word):
            w_groups, w_counts = getGroups(word)
            if w_groups != s_groups:
                return False
            for i in range(len(s_counts)):
                # If count in s is less than 3, count in word should be the same as count in s
                if s_counts[i] < 3 and s_counts[i] != w_counts[i]:
                    return False
                # If count in s is 3 or more, count in word should be less than or equal to count in s
                if s_counts[i] >= 3 and w_counts[i] > s_counts[i]:
                    return False
            return True

        return sum(isStretchy(word) for word in words)

This solution first identifies the groups and their counts in s and then does the same for each word. The comparison to check if a word is stretchy is based on the identified groups and counts.