[杨小白]_leetcode_力扣_11月25每日一题-809. 情感丰富的文字

120 阅读2分钟

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

前言

小白算法比较菜,希望能激励我每日更新,从leetcode第一题开始,2022年目标1900分,1823分了!!

11月25日每日一题

809. 情感丰富的文字

有时候人们会用重复写一些字母来表示额外的感受,比如 "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。

输入一组查询单词,输出其中可扩张的单词数量。

示例 1

  • 输入:
    • 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 中的单词都只由小写字母组成。

代码

很经典的字典树的解法,我看别人用数组写的字典树,不是很会写,一直都是用的Node类来写的字典树

缺点有二:1.建树有点慢; 2.占内存大

然后写一个test函数进行判断即可。树建起来了,就是算法逻辑了,直接模拟即可。

class Solution {
    Node root = new Node();

    public int expressiveWords(String s, String[] words) {
        Node cur = root;
        for (int i = 0; i < s.length(); i++) {
            int index = s.charAt(i) - 'a';
            if (cur.children[index] == null) {
                cur.children[index] = new Node();
            }
            cur = cur.children[index];
            int right = i;
            while (right < s.length() && s.charAt(right) == s.charAt(i)) {
                right++;
            }
            cur.val = right - i;
            i = right - 1;
        }
        int res = 0;
        for (int i = 0; i < words.length; i++) {
            if (test(words[i])) {
                res++;
            }
        }
        return res;
    }
    public boolean test(String s) {
        Node cur = root;
        for (int i = 0; i < s.length(); i++) {
            int index = s.charAt(i) - 'a';
            if (cur.children[index] == null) {
                return false;
            }
            cur = cur.children[index];
            int right = i;
            while (right < s.length() && s.charAt(right) == s.charAt(i)) {
                right++;
            }
            if (right - i > cur.val || (cur.val < 3 && right - i != cur.val)) {
                return false;
            }
            i = right - 1;
        }
        for (int i = 0; i < 26; i++) {
            if (cur.children[i]!=null) {
                return false;
            }
        }
        return true;
    }

    class Node {
        int val = 0;
        Node[] children = new Node[26];
    }
}

3.结束

1823分了。希望早日1900。knight最低是 1875.65,加油!

image.png