Sponsored
Sponsored
This approach involves building a trie that can be used to efficiently check if one word is a suffix of another. By storing only the unique paths in the trie, the encoding length can be minimized by pointing out the redundancies where one word is a suffix of another.
Time Complexity: O(N * K) where N is the number of words and K is the average length of a word.
Space Complexity: O(N * K) due to the storage in the Trie.
1using System;
2using System.Collections.Generic;
3
4class TrieNode {
5 public Dictionary<char, TrieNode> children = new Dictionary<char, TrieNode>();
6}
7
8class Solution {
9 public int MinimumLengthEncoding(string[] words) {
10 TrieNode root = new TrieNode();
11 HashSet<TrieNode> leaves = new HashSet<TrieNode>();
12
13 foreach (string word in words) {
14 TrieNode node = root;
15 for (int i = word.Length - 1; i >= 0; i--) {
16 if (!node.children.ContainsKey(word[i])) {
17 node.children[word[i]] = new TrieNode();
18 }
19 node = node.children[word[i]];
20 }
21 leaves.Add(node);
22 }
23
24 int length = 0;
25 foreach (TrieNode leaf in leaves) {
26 if (leaf.children.Count == 0) {
27 length += word.Length + 1;
28 }
29 }
30
31 return length;
32 }
33}
The C# solution mirrors the logic of inserting reversed words into a Trie. It examines nodes without children and sums the corresponding word lengths, including the additional '#' character.
By reverse sorting the words and checking suffix existence, it's possible to efficiently determine the redundant entries. This alternative approach utilizes set operations to ascertain unique encodings, optimizing storage by including only necessary components.
Time Complexity: O(N * K^2), Space Complexity: O(N * K).
1class Solution:
This method sorts the words by reversed string, facilitating checks for suffixes as subsequent entries. By discarding suffixes and iterating over the unique words, it computes the total length effectively.