- 情感丰富的文字
有时候人们会用重复写一些字母来表示额外的感受,比如 “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 中的单词都只由小写字母组成。
题解
就是统计每个字母的出现次数,如果不同,那么S中该字母数目必须大于等于3,才能让words扩充得到。
AC代码
class Solution {
public:
struct Node
{
char c;
int num;
};
vector<Node>a,b;
bool check(string s,string words)
{
a.clear();
b.clear();
Node t;
t.c=s[0],t.num=1;
a.push_back(t);
for(int i=1;i<s.length();i++)
{
int n=a.size()-1;
if(a[n].c==s[i])
a[n].num++;
else
{
t.c=s[i];
t.num=1;
a.push_back(t);
}
}
t.c=words[0],t.num=1;
b.push_back(t);
for(int i=1;i<words.length();i++)
{
int n=b.size()-1;
if(b[n].c==words[i])
b[n].num++;
else
{
t.c=words[i];
t.num=1;
b.push_back(t);
}
}
if(a.size()!=b.size())
return false;
//cout<<s<<" -- "<<words<<endl;
for(int i=0;i<a.size();i++)
{
//cout<<a[i].c<<" "<<a[i].num<<" "<<b[i].c<<" "<<b[i].num<<endl;
if(a[i].c!=b[i].c)return false;
if(a[i].num!=b[i].num&&(a[i].num<b[i].num||a[i].num<3))return false;
}
return true;
}
int expressiveWords(string s, vector<string>& words)
{
int res=0;
for(int i=0;i<words.size();i++)
if(check(s,words[i]))res++;
return res;
}
};