题目描述
给你一个字符串数组 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 由小写英文字母组成
求解思路
- 该题目就是一道简单的模拟题,解法也有很多,可以使用我们的前缀树,也就是字典树求解,当然直接暴力模拟也可以求解。
实现代码
暴力模拟
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);
}
}
运行结果

字符串前缀计数:利用字典树与暴力解法,
文章介绍了如何在给定字符串数组words中计算以特定字符串pref为前缀的项数。提供了两种解法,一种是简单的暴力遍历,另一种是使用Trie树进行优化。Trie树能更高效地处理前缀匹配问题。
3022

被折叠的 条评论
为什么被折叠?



