力扣 leetcode 809. 情感丰富的文字
问题描述
有时候人们会用重复写一些字母来表示额外的感受,比如 "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
。
输入一组查询单词,输出其中可扩张的单词数量。
提示:
1 <= s.length
,words.length <= 100
1 <= words[i].length <= 100
s
和所有在words
中的单词都只由小写字母组成。
示例
示例1:
输入:
s = "heeellooo"
words = ["hello", "hi", "helo"]
输出:1
解释:
我们能通过扩张 "hello" 的 "e" 和 "o" 来得到 "heeellooo"。
我们不能通过扩张 "helo" 来得到 "heeellooo" 因为 "ll" 的长度小于 3 。
解题思路
这题的解法是遍历字符数组,对每一个元素都与s
进行匹配,如果能匹配上,则cnt++
。根据匹配规则,我们可以先选取两个指针cursor
和j
,分别指向s
和words[i]
,当s[cursor] == words[i][j]
时,将cursor
和i
同时向后移动一位;当s[cursor] != words[i][j]
时,可能存在扩张操作。我们对此进行判断,由题意可知,如果存在扩张操作,则至少存在cursor - low + 1, cursor - low + 2,..., cursor, cursor + 1, cursor + 2, ..., cursor + high - 1
序列,满足:s[cursor - low + 1] == s[cursor - low + 2] == ... == s[cursor] == ... == s[cursor + high - 1]
, high - low > 4
。按照这个思路,实现代码:
class Solution {
public:
int expressiveWords(string s, vector<string>& words) {
int low, high;
int cnt = 0;
int cursor = 0;
bool flag = true;
for(int i = 0; i < words.size(); i++){
if(words[i][0] != s[0] || words[i].size() > s.size()){
// 先判断首字母和字符串长度是否匹配
continue;
}
cursor = 1;
flag = true;
for(int j = 1; j < words[i].size(); j++){
if(cursor >= s.size()){
flag = false;
break;
}
else if(words[i][j] != s[cursor]){
// 字符串不匹配时,判断是否存在扩张操作
low = cursor - 1;
high = cursor + 1;
while(low >= 0 && s[low] == s[cursor]){
low--;
}
while(high < s.size() && s[high] == s[cursor]){
high++;
}
// 存在扩张操作时,high - low > 3
if((high - low > 3) && high < s.size()){
cursor = high;
if(s[cursor] != words[i][j]){
flag = false;
break;
}
cursor++;
}
else{
flag = false;
break;
}
}
else{
// 字符串匹配,简单移动cursor即可
cursor++;
}
}
if(flag && cursor <= s.size()){
// 判断words[i]是否可扩张为s
while(cursor > 0 && s[cursor] == s[cursor - 1]){
cursor++;
}
if(cursor == s.size()){
cnt++;
}
}
}
return cnt;
}
};
本文来自博客园,作者:greatestchen},转载请注明原文链接:https://www.cnblogs.com/greatestchen/p/16927370.html