有时候人们会用重复写一些字母来表示额外的感受,比如 "hello" -> "heeellooo", "hi" -> "hiii"。我们将相邻字母都相同的一串字符定义为相同字母组,例如:"h", "eee", "ll", "ooo"。
对于一个给定的字符串 S ,如果另一个单词能够通过将一些字母组扩张从而使其和 S 相同,我们将这个单词定义为可扩张的(stretchy)。扩张操作定义如下:选择一个字母组(包含字母 c ),然后往其中添加相同的字母 c 使其长度达到 3 或以上。
例如,以 "hello" 为例,我们可以对字母组 "o" 扩张得到 "hellooo",但是无法以同样的方法得到 "helloo" 因为字母组 "oo" 长度小于 3。此外,我们可以进行另一种扩张 "ll" -> "lllll" 以获得 "helllllooo"。如果 S = "helllllooo",那么查询词 "hello" 是可扩张的,因为可以对它执行这两种扩张操作使得 query = "hello" -> "hellooo" -> "helllllooo" = S。
输入一组查询单词,输出其中可扩张的单词数量。
示例:
输入:
S = "heeellooo"
words = ["hello", "hi", "helo"]
输出:1
解释:
我们能通过扩张 "hello" 的 "e" 和 "o" 来得到 "heeellooo"。
我们不能通过扩张 "helo" 来得到 "heeellooo" 因为 "ll" 的长度小于 3 。
说明:
0 <= len(S) <= 100。
0 <= len(words) <= 100。
0 <= len(words[i]) <= 100。
S 和所有在 words 中的单词都只由小写字母组成。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/expressive-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
双指针法,
对于words里的每一个word,都用双指针和S扫一遍,
找到每一组对应的相同字母组的长度 cnt_i, cnt_j。
word 不能通过扩张得到 S 的可能性有:
1. 单个字母对不上,比如 S = "heeellooo", word = "hi", i 和 e 对不上。
2. S的字母组长度 cnt_i < 3, 而且 cnt_j != cnt_i,这种情况没办法扩张,因为扩张的结果长度必须大于等于3
3. cnt_i < cnt_j, 扩张只能越变越长
4. word 所有字母都用完了,S还有剩下没对应上的。
5. S 本身就比word 要短
时间复杂度:O((M + L) * N), M = len(S), N = len(words), L = max(len(word) for word in words
空间复杂度:O(1)
class Solution(object):
def expressiveWords(self, S, words):
"""
:type S: str
:type words: List[str]
:rtype: int
"""
res = 0
for word in words:
if len(S) < len(word): #情况5
continue
i, j = 0, 0
flag = 0
while i < len(S) and j < len(word):
if S[i] != word[j]: # 情况1
flag = 1
break
pre = S[i]
cnt_i = 0
while i < len(S) and S[i] == pre: # 找S字母组长度
i += 1
cnt_i += 1
cnt_j = 0
while j < len(word) and word[j] == pre: #找word字母组长度
j += 1
cnt_j += 1
if (cnt_i < 3 and cnt_i != cnt_j) or cnt_i < cnt_j:# 情况2 和 3
flag = 1
if not flag and i == len(S): # 情况4
res += 1
return res