友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
|
|
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

公众号的微信号是: jikerizhi。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
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。
输入一组查询单词,输出其中可扩张的单词数量。
示例:
输入: 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2026-07-04 22:31:50
*/
public int expressiveWords(String s, String[] words) {
Object[] data = get(s);
int result = 0;
List<Integer> cnt = (List<Integer>) data[1];
for (String word : words) {
Object[] wd = get(word);
if (!Objects.equals(data[0], wd[0])) {
continue;
}
List<Integer> wcnt = (List<Integer>) wd[1];
boolean flag = true;
for (int i = 0; i < cnt.size(); i++) {
Integer a = cnt.get(i);
Integer b = wcnt.get(i);
if (Objects.equals(a, b)) {
continue;
}
if (b > a || a < 3) {
flag = false;
break;
}
}
if (flag) {
result += 1;
}
}
return result;
}
private Object[] get(String s) {
List<Character> chars = new ArrayList<>();
List<Integer> count = new ArrayList<>();
chars.add(s.charAt(0));
count.add(1);
char[] array = s.toCharArray();
for (int i = 1; i < array.length; i++) {
if (array[i] == chars.getLast()) {
Integer cnt = count.removeLast();
count.add(cnt + 1);
} else {
chars.add(array[i]);
count.add(1);
}
}
return new Object[]{chars, count};
}

