原文链接:809. 情感丰富的文字 - 力扣(LeetCode)
题目
有时候人们会用重复写一些字母来表示额外的感受,比如 "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 。
提示:
1 <= s.length, words.length <= 100
1 <= words[i].length <= 100
s 和所有在 words 中的单词都只由小写字母组成。
题解
解题思路
利用双指针,依次对比待扩展字符串和目标字符串
1、存在字母种类不匹配的情况,返回false
2、存在待扩展字母数大于目标字母数,返回false
3、存在待扩展字母数和目标字母数不相等,且目标字母数小于3,返回false
class Solution {
public int expressiveWords(String s, String[] words) {
int res = 0;
for (String word : words) {
//判断每一个待扩展的字符串
if (expand(s, word)) {
res++;
}
}
return res;
}
public boolean expand(String s, String word) {
int i = 0, j = 0;
while (i<s.length() && j<word.length()) {
if (s.charAt(i) != word.charAt(j)) {
return false;
}
char temp = s.charAt(i);
//记录目标字符串中指定元素出现的次数
int counti = 0;
while(i < s.length() && s.charAt(i) == temp){
counti++;
i++;
}
//记录要扩张的字符串指定元素出现的次数
int countj = 0;
while (j < word.length() && word.charAt(j) == temp) {
countj++;
j++;
}
//扩展字符串的不能多与目标字符串的
if(counti < countj) {
return false;
}
//若要添加扩展字符串的字母,则必须大于3
//此时目标字符串的字母小于3时,则是不能成立的
if(counti != countj && counti < 3) {
return false;
}
}
//while循环结束,现在需要判断是否双指针都处于末尾处
//若不在则说明有一个提前退出,代表两个字符串的字母种类不匹配
return i == s.length() && j == word.length();
}
}
时间:1ms 空间:39.5MB