题目描述:
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
class Solution {
public:
int expressiveWords(string S, vector<string>& words) {
int result=0;
for(auto word:words) if(canExtend(S,word)) result++;
return result;
}
// extend的意思是t中一个字符相同的group可以变为s中一个长度大于2的group,所以t中的group长度更大也是可以的
bool canExtend(string s, string t)
{
if(t.size()>s.size()) return false;
int i=0;
int j=0;
while(i<s.size()&&j<t.size())
{
if(s[i]==t[j])
{
int k=i;
int count=1; // s中的group长度
while(k<s.size()-1&&s[k+1]==s[k])
{
k++;
count++;
}
if(count<=2) // 长度小于等于2,不能extend,只能让s[i]和t[j]匹配
{
i++;
j++;
}
else
{
i+=count;
j++;
while(t[j]==t[j-1]) j++; // 跳过t中的group
}
}
else return false;
}
return i==s.size()&&j==t.size();
}
};
本文介绍了一种字符串匹配算法,该算法判断一个单词是否可以通过拉伸某些字母组以匹配目标字符串。通过实例解释了拉伸匹配的概念,并提供了一个C++实现的解决方案。
601

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



