【LeetCode 809 情感丰富的文字】

【LeetCode809】 情感丰富的文字

有时候人们会用重复写一些字母来表示额外的感受,比如 “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 中的单词都只由小写字母组成

解题思路

使用两个指针来判断任意一个word能否扩展成字符串s。用指针i和j分别从字符串s和word的首位开始遍历。在遍历过程中,计算两者对应字符是否满足入下条件:

  1. 起始字符要相等,即 s [ i ] = w o r d [ j ] s[i] = word[j] s[i]=word[j];
  2. 假设以字符 s [ i ] s[i] s[i]开头且后续字符等于字符 s [ i ] s[i] s[i]的子串长度为 c o u n t 1 count1 count1; 假设以字符$ word[j]$开头且后续字符等于字符 w o r d [ j ] word[j] word[j]的子串长度为 c o u n t 2 count2 count2。要能满足扩展要求,那么 c o u n t 1 = c o u n t 2 count1 = count2 count1=count2 或者 c o u n t 1 > c o u n t 2 且 c o u n t 1 ≥ 3 count1 > count2 且count1 \geq 3 count1>count2count13

每次对比完一轮后,重新计算新子串的长度并比较是否条件,直到遍历完成,最后检查字符串s和word都遍历到了末尾。

	public int expressiveWords3(String s, String[] words) {
        int count = 0;
        for (String word : words) {
            if (canBeStretched(s, word)) {
                count++;
            }
        }
        return count;
    }

    private boolean canBeStretched(String s, String word) {
        int i = 0;
        int j = 0;
        while (i < s.length() && j < word.length()) {
            if (s.charAt(i) != word.charAt(j)) {
                return false;
            }

            int count1 = 0;
            char c1 = s.charAt(i);
            while (i < s.length() && c1 == s.charAt(i)) {
                count1++;
                i++;
            }

            int count2 = 0;
            char c2 = word.charAt(j);
            while (j < word.length() && c2 == word.charAt(j)) {
                count2++;
                j++;
            }


            if (count1 < count2) {
                return false;
            }

            if (count1 != count2 && count1 - count2 < 3) {
                return false;
            }
        }

        return i == s.length() && j == word.length();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值