Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // TrieNode.js file:
- --------------------
- export class TrieNode {
- #map;
- #wordQuantity;
- constructor() {
- this.map = new Map();
- this.wordQuantity = 0;
- }
- get map() {
- return this.#map;
- }
- get wordQuantity() {
- return this.#wordQuantity;
- }
- set map(i_Map) {
- this.#map = i_Map;
- }
- set wordQuantity(i_WordQuantity) {
- this.#wordQuantity = i_WordQuantity;
- }
- }
- --------------------
- // Trie.js file:
- import { TrieNode } from "./TrieNode.js";
- export class Trie {
- #root;
- constructor() {
- this.root = new TrieNode();
- }
- get root() {
- return this.#root;
- }
- set root(i_Root) {
- this.#root = i_Root;
- }
- insert(i_NewWord) {
- let current = this.root;
- for (const char of i_NewWord) {
- if (!current.map.has(char)) {
- current.map.set(char, new TrieNode());
- }
- current = current.map.get(char);
- }
- ++current.wordQuantity;
- }
- }
- --------------------
- // index.js file
- --------------------
- import { Trie } from "./Trie.js";
- import { TrieNode } from "./TrieNode.js";
- const strings = ["aa", "a", "ab", "aab"];
- // strings.sort(); // ["a", "aa", "aab", "ab"]
- const countPrefixPairs = (root, wordsCount, totalPairs) => {
- if (!root) {
- return;
- }
- if (root.wordQuantity > 0) {
- wordsCount += root.wordQuantity;
- totalPairs.ctr += wordsCount - 1;
- }
- root.map.forEach((currentNode) =>
- countPrefixPairs(currentNode, wordsCount, totalPairs)
- );
- };
- let trie = new Trie();
- for (const curStr of strings) {
- trie.insert(curStr);
- }
- let totalPairs = { ctr: 0 };
- countPrefixPairs(trie.root, 0, totalPairs);
- console.log(totalPairs);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement