Skip to content

Create 2416. Sum of Prefix Scores of Strings #595

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions 2416. Sum of Prefix Scores of Strings
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Trie Node definition
class trie {
public:
int x; // To store how many times the prefix ending at this node has been seen.
trie *v[26]; // Array of pointers to children nodes for each character 'a' to 'z'.
};

// Function to insert a string into the Trie and update prefix counts
void maketrie(string str, trie* node) {
for (auto &i: str) { // Traverse each character in the string
// If the node for this character doesn't exist, create it
if (node->v[i - 'a'] == NULL) {
node->v[i - 'a'] = new trie(); // Create a new Trie node
node = node->v[i - 'a']; // Move to the newly created node
node->x = node->x + 1; // Increment the count for this prefix
} else {
node = node->v[i - 'a']; // Move to the existing node
node->x = node->x + 1; // Increment the count for this prefix
}
}
}

// Function to calculate the sum of prefix scores for a given string
void solve(string str, trie* node, int &x) {
trie* p = node; // Pointer to traverse the Trie
for (auto &i: str) { // Traverse each character in the string
p = p->v[i - 'a']; // Move to the next node in the Trie
x += p->x; // Add the count of this prefix to the total score
}
}

// Main solution class
class Solution {
public:
// Function to calculate sum of prefix scores for all words
vector<int> sumPrefixScores(vector<string>& words) {
trie *node = new trie(); // Create the root node of the Trie

// Step 1: Insert each word into the Trie and build the prefix tree
for (auto &i: words) {
maketrie(i, node); // Insert word into the Trie
}

vector<int> ans; // Vector to store the final prefix scores
int x = 0; // Variable to store the current score for a word

// Step 2: Calculate the prefix score for each word
for (auto &i: words) {
x = 0; // Reset the score for the new word
solve(i, node, x); // Calculate the prefix score for the current word
ans.push_back(x); // Store the score in the answer vector
}

return ans; // Return the final list of prefix scores
}
};
Loading