算法初探LeetCode-情感丰富的文字

100 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第29天,点击查看活动详情

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 。

提示:

0 <= len(S) <= 1000 <= len(words) <= 1000 <= len(words[i]) <= 100。
S 和所有在 words 中的单词都只由小写字母组成。
通过次数6,710提交次数16,071

思路分析

根据题意分析,采用反证法,一共有3种不可扩充情况

  • 1:S串和words[i]串对应字符不相同
  • 2:S串中的某个字符的扩张幅度<3且跟 words[I]串中某个字符的数目不相同
  • 3:S串中对应字符小于words[i]串的数目

算法代码

public int expressiveWords(String S, String[] words) {
    int res = 0;
    for (String word: words) {
        if (canStretch(word.toCharArray(), S.toCharArray()))
            res++;
    }
    return res;
}

private boolean canStretch(char[] word, char[] target) {
    int i = 0, j = 0;
    while (i < word.length && j < target.length) {
        if (word[i] != target[j]) return false;

        char ch = word[i];

        int count1 = 0;
        while (i < word.length && word[i] == ch) {
            count1++;
            i++;
        }

        int count2 = 0;
        while (j < target.length && target[j] == ch) {
            count2++;
            j++;
        }

        if (count1 == count2) continue;
        if (count1 > count2) return false;
        if (count2 < 3) return false;
    }

    return i == word.length && j == target.length;
}

结果详情

Snipaste_2022-12-27_21-34-14.png

算法复杂度

  • 空间复杂度:O(n)O(n)
  • 时间复杂度:O(n2)O(n^2)

掘金(JUEJIN)一起进步,一起成长!