题目描述:
有时候人们会用重复写一些字母来表示额外的感受,比如 “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 。
分析:
这道理主要是考察words中的元素word是否能通过扩展变成S。能扩展的要求:
- word和S中的字母顺序要求一致
- word中某字母数量要小于S中对应字母数量,且S中的字母数量要大于等于3。
在两者中某字母数量不等时,如果word中某字母数量大于S中对应的字母或者S中该字母数量小于3,则不能扩展。如果某字母数量一样,可以直接跳过。
代码实现:
class Solution {
public:
int canextend(string &word, string &target) {
auto s = word.c_str(),t=target.c_str();
while(*s && *t){//遍历整个词
if(*s!=*t) return 0;
char c=*s;
int cnt1=0, cnt2=0;
for(;*s==c;++s,++cnt1);//用两个for可以把连续相同的字符统计完,统计word和target中c的数量。
for(;*t==c;++t,++cnt2);
if((cnt1>cnt2 || cnt2<3) && cnt1!=cnt2){//如果cnt1和cnt2相等,则可能是两个小于3且相等则不用拓展
return 0;
}
}
return *s==*t;
}
int expressiveWords(string S, vector<string>& words) {
int ret = 0;
for(auto &word:words){
if(word.size()>=S.size()) continue;
ret += canextend(word,S);
}
return ret;
}
};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/expressive-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
参考:
https://leetcode-cn.com/problems/expressive-words/comments/120102