-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path14.LongestCommonPrefix.cs
82 lines (72 loc) · 2.2 KB
/
14.LongestCommonPrefix.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//14. Longest Common Prefix
//Write a function to find the longest common prefix string amongst an array of strings.
//If there is no common prefix, return an empty string "".
public class Solution
{
public string LongestCommonPrefix(string[] strs)
{
int size = strs.Length;
if (size == 0)
return "";
if (size == 1)
return strs[0];
//Sort the array of strings
//The first and last strings will be the smallest and largest strings
//We can compare the first and last strings to find the longest common prefix
Array.Sort(strs);
int end = Math.Min(strs[0].Length, strs[size - 1].Length);
int i = 0;
while (i < end && strs[0][i] == strs[size - 1][i])
i++;
String pre = strs[0].Substring(0, i);
return pre;
}
}
//Trie
public class Solution
{
public string LongestCommonPrefix(string[] strs)
{
if (strs == null || strs.Length == 0)
return "";
Trie root = new();
foreach (var word in strs)
root.Insert(word);
return root.LongestPrefix();
}
public class Trie
{
private bool isEndOfWord;
private readonly Dictionary<char, Trie> children;
public Trie()
{
children = new Dictionary<char, Trie>();
isEndOfWord = false;
}
public void Insert(string word)
{
var current = this;
foreach (char c in word)
{
if (!current.children.ContainsKey(c))
current.children[c] = new Trie();
current = current.children[c];
}
current.isEndOfWord = true;
}
public string LongestPrefix()
{
var prefix = new System.Text.StringBuilder();
var current = this;
while (current.children.Count == 1 && !current.isEndOfWord)
{
foreach (var child in current.children) // Always 1 child
{
prefix.Append(child.Key);
current = child.Value;
}
}
return prefix.ToString();
}
}
}