元宝 LeetCode 2416.字符串的前缀分数和 C++实现
·
下面给你 LeetCode 2416《字符串的前缀分数和》 的 C++ 标准实现,思路仍然是 Trie + 前缀计数,时间复杂度最优 ✅
✅ C++ 实现(推荐写法)
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
struct TrieNode {
int cnt = 0;
TrieNode* children[26] = {nullptr};
};
TrieNode* root = new TrieNode();
// 插入单词到 Trie
void insert(const string& word) {
TrieNode* node = root;
for (char c : word) {
int idx = c - 'a';
if (!node->children[idx]) {
node->children[idx] = new TrieNode();
}
node = node->children[idx];
node->cnt++; // 经过该前缀的单词数 +1
}
}
// 计算单个单词的前缀分数
int query(const string& word) {
TrieNode* node = root;
int score = 0;
for (char c : word) {
node = node->children[c - 'a'];
score += node->cnt;
}
return score;
}
public:
vector<int> sumPrefixScores(vector<string>& words) {
// 建 Trie
for (const string& w : words) {
insert(w);
}
// 计算结果
vector<int> ans(words.size());
for (int i = 0; i < words.size(); ++i) {
ans[i] = query(words[i]);
}
return ans;
}
};
🚀 复杂度分析
| 项目 | 复杂度 |
|---|---|
| 构建 Trie | O(总字符数) |
| 查询 | O(总字符数) |
| 空间 | O(总字符数) |
✅ 适用于最大数据规模(10⁵ 字符串)
📌 示例
words = {"abc","ab","bc","b"}
输出 = {5, 4, 3, 2}
🧠 为什么 C++ 写法高效?
-
使用 数组指针
TrieNode* children[26] -
无
unordered_map开销 -
内存连续,缓存友好
-
完全符合 LeetCode 判题性能要求
✅ 可选优化(进阶)
-
使用 静态数组 + 索引池(避免
new,更快) -
使用
vector<int>代替指针(竞赛常用)
如果你需要:
-
✅ 静态数组版(最快)
-
✅ 内存释放版
-
✅ Python / Java 对照版
-
✅ 一步步手动画 Trie
可以直接告诉我 👍
更多推荐

所有评论(0)