Before we dive into the solution, let’s clarify the problem statement a bit:
s
.words
.s
.s
by expanding some of its characters into a group of repeated characters.s
already forms a group of repeated characters of length 3 or more.s
and each word in words
. This helps in comparing the structure.s
.s
can extend to at least 3 for “stretchiness” but not vice versa.s
with each word to determine “stretchiness”.def expressive_words(s: str, words: list) -> int:
def get_char_groups(word):
groups = []
i, n = 0, len(word)
while i < n:
char = word[i]
count = 0
while i < n and word[i] == char:
i += 1
count += 1
groups.append((char, count))
return groups
def is_stretchy(s_group, w_group):
if len(s_group) != len(w_group):
return False
for (sc, sc_count), (wc, wc_count) in zip(s_group, w_group):
if sc != wc:
return False
if sc_count < wc_count:
return False
if sc_count > wc_count and sc_count < 3:
return False
return True
s_group = get_char_groups(s)
count_stretchy_words = 0
for word in words:
w_group = get_char_groups(word)
if is_stretchy(s_group, w_group):
count_stretchy_words += 1
return count_stretchy_words
# Example Usage
s = "heeellooo"
words = ["hello", "hi", "helo"]
print(expressive_words(s, words)) # Output: 1
get_char_groups
function runs in O(n) where n is the length of the word involved, since it involves a single scan of the word.is_stretchy
runs in O(k) where k is the number of groups in the word.expressive_words
is O(n * m) where n is the length of s
and m is the average length of words in the list since each word in words
is processed individually.This solution should efficiently determine the number of stretchy words relative to the string s
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?