Skip to content

Commit f70036a

Browse files
Create 809. 情感丰富的文字.md
1 parent 7ad9665 commit f70036a

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#### 809. 情感丰富的文字
2+
3+
难度:中等
4+
5+
---
6+
7+
有时候人们会用重复写一些字母来表示额外的感受,比如 `"hello" -> "heeellooo"`, `"hi" -> "hiii"`。我们将相邻字母都相同的一串字符定义为相同字母组,例如:"h", "eee", "ll", "ooo"。
8+
9+
对于一个给定的字符串 S ,如果另一个单词能够通过将一些字母组扩张从而使其和 S 相同,我们将这个单词定义为可扩张的(stretchy)。扩张操作定义如下:选择一个字母组(包含字母 `c` ),然后往其中添加相同的字母 `c` 使其长度达到 3 或以上。
10+
11+
例如,以 "hello" 为例,我们可以对字母组 "o" 扩张得到 "hellooo",但是无法以同样的方法得到 "helloo" 因为字母组 "oo" 长度小于 3。此外,我们可以进行另一种扩张 "ll" -> "lllll" 以获得 "helllllooo"。如果 `s = "helllllooo"`,那么查询词 "hello" 是可扩张的,因为可以对它执行这两种扩张操作使得 `query = "hello" -> "hellooo" -> "helllllooo" = s`
12+
13+
输入一组查询单词,输出其中可扩张的单词数量。
14+
15+
**示例:**
16+
17+
```
18+
输入:
19+
s = "heeellooo"
20+
words = ["hello", "hi", "helo"]
21+
输出:1
22+
解释:
23+
我们能通过扩张 "hello" 的 "e" 和 "o" 来得到 "heeellooo"。
24+
我们不能通过扩张 "helo" 来得到 "heeellooo" 因为 "ll" 的长度小于 3 。
25+
```
26+
27+
**提示:**
28+
29+
* `1 <= s.length, words.length <= 100`
30+
* `1 <= words[i].length <= 100`
31+
* s 和所有在 `words` 中的单词都只由小写字母组成。
32+
33+
---
34+
35+
双指针:在每次判断中,将两个指针分别指向 `s``word`,再用两个常数 `len1``len2` 分别记录当前指针所指向字符的长度,以下为不是可扩张的单词的情况:
36+
37+
- `len1 < len2`
38+
- `len1 != len2 && len1 < 3`
39+
40+
当恰好均遍历完 `s``word` 时,即指针恰好均指向字符串最后一个字符的后一位时,该单词则是可扩张的。
41+
42+
```java
43+
class Solution {
44+
public int expressiveWords(String s, String[] words) {
45+
int ans = 0;
46+
for(String word: words){
47+
if(check(s, word)) ans++;
48+
}
49+
return ans;
50+
}
51+
52+
private boolean check(String s, String word){
53+
int i = 0, j = 0;
54+
while(i < s.length() && j < word.length()){
55+
if(s.charAt(i) != word.charAt(j)) return false;
56+
char ch = s.charAt(i);
57+
int len1 = 0, len2 = 0;
58+
while(i < s.length() && s.charAt(i) == ch){
59+
len1++;
60+
i++;
61+
}
62+
while(j < word.length() && word.charAt(j) == ch){
63+
len2++;
64+
j++;
65+
}
66+
if(len1 != len2 && len1 < 3) return false;
67+
if(len1 < len2) return false;
68+
}
69+
return i == s.length() && j == word.length();
70+
}
71+
}
72+
```
73+

0 commit comments

Comments
 (0)