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).
1using System;
2using System.Collections.Generic;
class Solution {
public int MinimumLengthEncoding(string[] words) {
HashSet<string> uniqueWords = new HashSet<string>(words);
List<string> sortedWords = new List<string>(uniqueWords);
sortedWords.Sort((a, b) => string.Compare(b, a, StringComparison.Ordinal));
foreach (string word in sortedWords) {
for (int i = 1; i < word.Length; i++) {
uniqueWords.Remove(word.Substring(i));
}
}
int length = 0;
foreach (string word in uniqueWords) {
length += word.Length + 1;
}
return length;
}
}
The solution in C# benefits from the sorted word manipulation and distinct word tracking methods, efficiently computing valid encodings with required components and separators.