LeetCode解題-#14-Longest Common Prefix
題目描述:
找出一組字串中的最長共同字首。
分析:
例如 abc, abd, ab,它們的最長共同字首是 ab。
思路:
學習過的 Trie 剛好能解決這個問題,雖然不會是最優解,但可以練練手。
Trie:http://blog.csdn.net/cuit/article/details/78495561
先定義好 Trie 樹 的資料結構:
這裡用 HashMap(C#中是 Dictionary)儲存樹的子結點,優點是不用儲存多餘的空陣列元素。
只實現了一個 Add(string s) 方法,用於新增字串。
public class Trie
{
public TrieNode Root;
public Trie()
{
Root = new TrieNode();
}
public void Add(string s)
{
TrieNode runNode = Root;
for (int i = 0; i < s.Length; i++)
{
var children = runNode.Children;
char c = s[i];
TrieNode next = null;
if (children.TryGetValue(c, out next))
{
next = children[c];
}
if (next == null)
{
children.Add(c, new TrieNode());
}
runNode = children[c];
}
runNode.IsEnd = true;
}
}
public class TrieNode
{
public bool IsEnd { get; set; }
public Dictionary<char,TrieNode> Children { get; set; }
public TrieNode()
{
Children = new Dictionary<char, TrieNode>();
IsEnd = false;
}
}
然後依次把字串陣列插入Trie中,然後只要找到子結點的數量等於 1 且還有子結點時,即表示這些字串還在共同字首的樹枝中,反正即表示有分支了,也即這些字串不再有共同字首了。
public string LongestCommonPrefix(string[] strs) {
if(strs.Length == 0)
{
return "";
}
Trie t = new Trie();
for(int i = 0; i < strs.Length; i++)
{
t.Add(strs[i]);
}
StringBuilder sb = new StringBuilder();
TrieNode runNode = t.Root;
while (runNode.Children.Count == 1 && !runNode.IsEnd)
{
var keys = runNode.Children.Keys;
foreach(var k in keys)
{
sb.Append(k);
runNode = runNode.Children[k];
}
}
return sb.ToString();
}
相關文章
- LeetCode 第 14 題(Longest Common Prefix)LeetCode
- Leetcode Longest Common PrefixLeetCode
- [LeetCode]Longest Common PrefixLeetCode
- Leetcode 14 Longest Common PrefixLeetCode
- Leetcode-Longest Common PrefixLeetCode
- Longest Common Prefix leetcode javaLeetCodeJava
- [LeetCode] Longest Common Prefix 最長共同字首LeetCode
- C# 寫 LeetCode easy #14 Longest Common PrefixC#LeetCode
- leetcode學習筆記14 Longest Common PrefixLeetCode筆記
- LeetCode Longest Common Prefix(014)解法總結LeetCode
- Longest Common Prefix字串最長公共字首問題字串
- LeetCode - 014 - 最長公共字首(longest-common-prefix)LeetCode
- LeetCode | 14. Longest Common Prefix的三種演算法LeetCode演算法
- LeetCode- Implement Trie (Prefix Tree)LeetCode
- LeetCode之Find Common Characters(Kotlin)LeetCodeKotlin
- LeetCode-Lowest Common Ancestor of a Binary TreLeetCode
- [leetcode 題解] 849LeetCode
- Leetcode 全套題解LeetCode
- 「LeetCode」全部題解LeetCode
- LeetCode Greatest Common Divisor of Strings All In OneLeetCode
- leetcode題解(陣列問題)LeetCode陣列
- Leetcode題解1-50題LeetCode
- Leetcode 565 & 240 題解LeetCode
- LeetCode 解題彙總LeetCode
- leetcode解題目錄LeetCode
- E - Prefix Equality
- leetcode題解(查詢表問題)LeetCode
- LeetCode題解第122題LeetCode
- leetcode題解【持續更新】LeetCode
- 【leetcode 399 周賽】【題解】LeetCode
- Prefix Flip (Easy Version)
- Natasha, Sasha and the Prefix Sums
- IP-Prefix List
- Leetcode已刷題目題解彙總LeetCode
- leetcode題解(動態規劃)LeetCode動態規劃
- 用指令碼整理Leetcode題解指令碼LeetCode
- [LeetCode解題] -- 零錢兌換LeetCode
- LeetCode 題解(252) : Find the Duplicate NumberLeetCode