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中文網其他相關文章!