|
| 1 | +// Trie Node definition |
| 2 | +class trie { |
| 3 | + public: |
| 4 | + int x; // To store how many times the prefix ending at this node has been seen. |
| 5 | + trie *v[26]; // Array of pointers to children nodes for each character 'a' to 'z'. |
| 6 | +}; |
| 7 | + |
| 8 | +// Function to insert a string into the Trie and update prefix counts |
| 9 | +void maketrie(string str, trie* node) { |
| 10 | + for (auto &i: str) { // Traverse each character in the string |
| 11 | + // If the node for this character doesn't exist, create it |
| 12 | + if (node->v[i - 'a'] == NULL) { |
| 13 | + node->v[i - 'a'] = new trie(); // Create a new Trie node |
| 14 | + node = node->v[i - 'a']; // Move to the newly created node |
| 15 | + node->x = node->x + 1; // Increment the count for this prefix |
| 16 | + } else { |
| 17 | + node = node->v[i - 'a']; // Move to the existing node |
| 18 | + node->x = node->x + 1; // Increment the count for this prefix |
| 19 | + } |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +// Function to calculate the sum of prefix scores for a given string |
| 24 | +void solve(string str, trie* node, int &x) { |
| 25 | + trie* p = node; // Pointer to traverse the Trie |
| 26 | + for (auto &i: str) { // Traverse each character in the string |
| 27 | + p = p->v[i - 'a']; // Move to the next node in the Trie |
| 28 | + x += p->x; // Add the count of this prefix to the total score |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +// Main solution class |
| 33 | +class Solution { |
| 34 | +public: |
| 35 | + // Function to calculate sum of prefix scores for all words |
| 36 | + vector<int> sumPrefixScores(vector<string>& words) { |
| 37 | + trie *node = new trie(); // Create the root node of the Trie |
| 38 | + |
| 39 | + // Step 1: Insert each word into the Trie and build the prefix tree |
| 40 | + for (auto &i: words) { |
| 41 | + maketrie(i, node); // Insert word into the Trie |
| 42 | + } |
| 43 | + |
| 44 | + vector<int> ans; // Vector to store the final prefix scores |
| 45 | + int x = 0; // Variable to store the current score for a word |
| 46 | + |
| 47 | + // Step 2: Calculate the prefix score for each word |
| 48 | + for (auto &i: words) { |
| 49 | + x = 0; // Reset the score for the new word |
| 50 | + solve(i, node, x); // Calculate the prefix score for the current word |
| 51 | + ans.push_back(x); // Store the score in the answer vector |
| 52 | + } |
| 53 | + |
| 54 | + return ans; // Return the final list of prefix scores |
| 55 | + } |
| 56 | +}; |
0 commit comments