Skip to content
Merged
Show file tree
Hide file tree
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
47 changes: 47 additions & 0 deletions solution/2400-2499/2416.Sum of Prefix Scores of Strings/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,53 @@ function sumPrefixScores(words: string[]): number[] {
}
```

#### JavaScript

```js
class Trie {
constructor() {
this.children = {};
this.cnt = 0;
}

insert(w) {
let node = this;
for (const c of w) {
if (!node.children[c]) {
node.children[c] = new Trie();
}
node = node.children[c];
node.cnt++;
}
}

search(w) {
let node = this;
let ans = 0;
for (const c of w) {
if (!node.children[c]) {
return ans;
}
node = node.children[c];
ans += node.cnt;
}
return ans;
}
}

/**
* @param {string[]} words
* @return {number[]}
*/
var sumPrefixScores = function (words) {
const trie = new Trie();
for (const w of words) {
trie.insert(w);
}
return words.map(w => trie.search(w));
};
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,53 @@ function sumPrefixScores(words: string[]): number[] {
}
```

#### JavaScript

```js
class Trie {
constructor() {
this.children = {};
this.cnt = 0;
}

insert(w) {
let node = this;
for (const c of w) {
if (!node.children[c]) {
node.children[c] = new Trie();
}
node = node.children[c];
node.cnt++;
}
}

search(w) {
let node = this;
let ans = 0;
for (const c of w) {
if (!node.children[c]) {
return ans;
}
node = node.children[c];
ans += node.cnt;
}
return ans;
}
}

/**
* @param {string[]} words
* @return {number[]}
*/
var sumPrefixScores = function (words) {
const trie = new Trie();
for (const w of words) {
trie.insert(w);
}
return words.map(w => trie.search(w));
};
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class Trie {
constructor() {
this.children = {};
this.cnt = 0;
}

insert(w) {
let node = this;
for (const c of w) {
if (!node.children[c]) {
node.children[c] = new Trie();
}
node = node.children[c];
node.cnt++;
}
}

search(w) {
let node = this;
let ans = 0;
for (const c of w) {
if (!node.children[c]) {
return ans;
}
node = node.children[c];
ans += node.cnt;
}
return ans;
}
}

/**
* @param {string[]} words
* @return {number[]}
*/
var sumPrefixScores = function (words) {
const trie = new Trie();
for (const w of words) {
trie.insert(w);
}
return words.map(w => trie.search(w));
};
Loading