【LeetCode每日一题:2185. 统计包含给定前缀的字符串~~~暴力模拟+前缀树+JavaAPI】

题目描述

给你一个字符串数组 words 和一个字符串 pref 。

返回 words 中以 pref 作为 前缀 的字符串的数目。

字符串 s 的 前缀 就是 s 的任一前导连续字符串。

示例 1:

输入:words = [“pay”,“attention”,“practice”,“attend”], pref = “at”
输出:2
解释:以 “at” 作为前缀的字符串有两个,分别是:“attention” 和 “attend” 。
示例 2:

输入:words = [“leetcode”,“win”,“loops”,“success”], pref = “code”
输出:0
解释:不存在以 “code” 作为前缀的字符串。

提示:

1 <= words.length <= 100
1 <= words[i].length, pref.length <= 100
words[i] 和 pref 由小写英文字母组成

求解思路

  1. 该题目就是一道简单的模拟题,解法也有很多,可以使用我们的前缀树,也就是字典树求解,当然直接暴力模拟也可以求解。

实现代码

暴力模拟

class Solution {
    public int prefixCount(String[] words, String pref) {
        int cnt=0;
        for(String str:words){
            if(str.length()<pref.length()) continue;
            String s=str.substring(0,pref.length());
            if(pref.equals(s)) cnt++;
        }
        return cnt;
    }
}

JavaAPI方法

class Solution {
    public int prefixCount(String[] words, String pref) {
        int res = 0;
        for (String word : words) {
            if (word.startsWith(pref)) {
                res++;
            }
        }
        return res;
    }
}

前缀树

class Solution {
    Trie root;

    class Trie {
        int cnt;
        Trie[] children;

        public Trie() {
            cnt = 0;
            children = new Trie[26];
        }
    }

    public void addWord(String word) {
        Trie node = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (node.children[c - 'a'] == null) {
                node.children[c - 'a'] = new Trie();
            }
            node.children[c - 'a'].cnt++;
            node = node.children[c - 'a'];
        }
    }

    public int cntPrefix(String prefix) {
        Trie node = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (node.children[c - 'a'] == null) {
                return 0;
            }
            node = node.children[c - 'a'];
        }
        return node.cnt;
    }

    public int prefixCount(String[] words, String pref) {
        root = new Trie();
        for (String word : words) {
            addWord(word);
        }
        return cntPrefix(pref);
    }
}

运行结果

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

硕风和炜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值