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.
题意分析
个人觉得反向理解更加容易些。S为stretched word, 问哪些string in words可以由S压缩得到。但是不是所有的characters in S都可以压缩。只有在character的length >= 3的时候才可以。结合例子梳理一下,"heeellooo"为stretched word, character 'e' and 'o' count >= 3 可以压缩。"heeellooo" 压缩e and o可以得到"hello";"heeellooo"中不含'i',所以不可能压缩得到"hi";"heeellooo"中"ll"只有两个count不能压缩,所以"helo"也不可以压缩得到。
主要的难点在于有3的这个限制。
解题
大方向,写一个function解决当前word是否可以由S压缩得到。
对比两条string的可以尝试two pointer,然后分情况讨论:[p1指向S,p2指向word]
1. S[p1] = word[p2] 很好 --> p1 += 1; p2 += 1
2. S[p1] != word[p2] 判断时候可以压缩
a.S[p1-1] = S[p1] && S[p1] = S[p+1]: S[p1]和前后两个character相同 --> p1+= 1 only
b.S[p1-1] = S[p1] && S[p1] = S[p-2]: S[p1]和前两个character相同 --> p1+=1 only
c.以上都不符合 --> return False
为什么只有a and b case,p1所在的位置只有可能在重复string的最后一个(b)和中间(a)
最后还需要check在遍历完S的时候,word是否也遍历完了
如何遍历?
p1每次loop都会增加但是p2并不一定,所以遍历S会更加好一些
class Solution:
def expressiveWords(self, S: str, words: List[str]) -> int:
count = 0
for word in words:
if(self.isValid(S, word)):
count += 1
return count
def isValid(self, S: str, word: str) -> bool:
p2 = 0
for p1 in range(len(S)):
if p2<len(word) and S[p1]==word[p2]:
p2 += 1
elif not ((p1>0 and p1+1<len(S) and S[p1]==S[p1-1] and S[p1]==S[p1+1]) or
(p1>1 and S[p1]==S[p1-1] and S[p1]==S[p1-2])):
return False
return p2==len(word)
博客分析了LeetCode 809题目的解题思路,强调了stretched word的概念,即只有当字符出现次数>=3时才能压缩。通过two pointer方法,分别对应S和word的指针,进行比较和判断。在字符不匹配时,根据特定条件更新指针位置。文章指出,只有在特定情况下才能使word由S压缩得到,并提供了遍历策略。

被折叠的 条评论
为什么被折叠?



