2416。字符串前缀分数之和
难度:难
主题:数组、字符串、Trie、计数
给你一个大小为 n 的单词数组,由 非空 字符串组成。
我们将字符串单词的分数定义为字符串单词[i]的数量,这样单词就是单词[i]的前缀。
返回大小为n的数组答案,其中answer[i]是单词[i]的每个非空前缀分数的总和。
注意字符串被视为其自身的前缀。
示例1:
示例2:
约束:
提示:
解决方案:
我们可以使用 Trie 数据结构,它对于处理前缀特别有效。 Trie 中的每个节点都代表单词的一个字母,我们将在每个节点维护一个计数器来存储遇到该前缀的次数。这使我们能够通过计算有多少个单词以该前缀开头来有效地计算每个前缀的分数。
将单词插入 Trie:
计算前缀分数:
构建答案数组:
让我们用 PHP 实现这个解决方案:2416。字符串前缀分数之和
<?php class TrieNode { /** * @var array */ public $children; /** * @var int */ public $count; public function __construct() { $this->children = []; $this->count = 0; } } class Trie { /** * @var TrieNode */ private $root; public function __construct() { $this->root = new TrieNode(); } /** * Insert a word into the Trie and update the prefix counts * * @param $word * @return void */ public function insert($word) { ... ... ... /** * go to ./solution.php */ } /** * Get the sum of prefix scores for a given word * * @param $word * @return int */ public function getPrefixScores($word) { ... ... ... /** * go to ./solution.php */ } } /** * @param String[] $words * @return Integer[] */ function sumOfPrefixScores($words) { ... ... ... /** * go to ./solution.php */ } // Example usage: $words1 = ["abc", "ab", "bc", "b"]; $words2 = ["abcd"]; print_r(sumOfPrefixScores($words1)); // Output: [5, 4, 3, 2] print_r(sumOfPrefixScores($words2)); // Output: [4] ?>
TrieNode 类:
特里类:
主要函数(sumOfPrefixScores):
For words = ["abc", "ab", "bc", "b"], the output will be:
Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 )
This approach ensures that we efficiently compute the prefix scores in linear time relative to the total number of characters in all words.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
以上是字符串前缀分数之和的详细内容。更多信息请关注PHP中文网其他相关文章!