算法总结 - 字符串 - 字符压缩与延伸

算法总结 - 字符串 - 字符压缩与延伸

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 =
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值