算法总结 - 字符串 - 字符压缩与延伸
809. Expressive Words
Sometimes people repeat letters to represent extra feeling, such as “hello” -> “heeellooo”, “hi” -> “hiiii”. In these strings like “heeellooo”, we have groups of adjacent letters that are all the same: “h”, “eee”, “ll”, “ooo”.
For some given string S, a query word is stretchy if it can be made to be equal to S by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is 3 or more.
For example, starting with “hello”, we could do an extension on the group “o” to get “hellooo”, but we cannot get “helloo” since the group “oo” has size less than 3. Also, we could do another extension like “ll” -> “lllll” to get “helllllooo”. If S = “helllllooo”, then the query word “hello” would be stretchy because of these two extension operations: query = “hello” -> “hellooo” -> “helllllooo” = S.
Given a list of query words, return the number of words that are stretchy.
Example:
Input:
S = “heeellooo”
words = [“hello”, “hi”, “helo”]
Output: 1
Explanation:
We can extend “e” and “o” in the word “hello” to get “heeellooo”.
We can’t extend “helo” to get “heeellooo” because the group “ll” is not size 3 or more.
Abstract
- 给出了一个字符串,其中有些字母是为了表现“情绪”而重复出现了多次
- 给出了一个字符串数组,求有多少个字符串可以产生这样的情绪化词
- 表现语气最少需要一个字母重复三次。
Idea
- 简化情绪化次或者延伸候选字符串
Question to ask
- 怎么化简一个情绪词?
Solution
- 把情绪词和候选字符串每个字符依次对比, 一下情况不能构造情绪词
- 字符相同, 情绪词重复字符的次数小于3且不等于候选字符串重复次数
- 字符相同,情绪词重复字符次数小于候选字符串次数
- 字符不同
Code
public int expressiveWords(String S, String[] words) {
int cnt = 0;
for (String s: words){
// m1
if (helper(S, s)) cnt++;
}
return cnt;
}
private boolean helper(String s, String t){
int i = 0;
int j =