## 题目描述：

LeetCode 809. Expressive Words

Sometimes people repeat letters to represent extra feeling, such as "hello" -> "heeellooo", "hi" -> "hiiii".  Here, we have groups, of adjacent letters that are all the same character, and adjacent characters to the group are different.  A group is extended if that group is length 3 or more, so "e" and "o" would be extended in the first example, and "i" would be extended in the second example.  As another example, the groups of "abbcccaaaa" would be "a", "bb", "ccc", and "aaaa"; and "ccc" and "aaaa" are the extended groups of that string.

For some given string S, a query word is stretchy if it can be made to be equal to S by extending some groups.  Formally, we are allowed to repeatedly choose a group (as defined above) of characters `c`, and add some number of the same character `c` to it so that the length of the group is 3 or more.  Note that we cannot extend a group of size one like "h" to a group of size two like "hh" - all extensions must leave the group extended - ie., at least 3 characters long.

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 extended.
```

Notes:

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

## Python代码：

``````class Solution(object):
def expressiveWords(self, S, words):
"""
:type S: str
:type words: List[str]
:rtype: int
"""
cs = self.countLetters(S)
ans = 0
for word in words:
ws = self.countLetters(word)
ans += self.checkWords(cs, ws)
return ans
def countLetters(self, S):
cnt, lc = 0, ''
ans = []
for c in S:
if c == lc:
cnt += 1
else:
if cnt: ans.append((lc, cnt))
cnt, lc = 1, c
if cnt: ans.append((lc, cnt))
return ans
def checkWords(self, cs, ws):
if len(cs) != len(ws): return 0
for c, w in zip(cs, ws):
if c != w: return 0
if c < w: return 0
if c != w and c < 3: return 0
return 1
``````

Pingbacks已关闭。