0014. Longest Common Prefix
Easy | String + Trie | 16 ms (94.87%), 13.7 MB (39.95%)
Source: LeetCode - Longest Common Prefix GitHub: Solution / Performance
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 ""
.
Instead of sorting the list of strings and find the answer between the longest string and shortest string, we could use the Trie data structure to find the answer. (Refer to 0208. Implement Trie)
We iterate through each word in the list to insert the characters plus the symbol of the end of word # into the Trie. Then, we traverse the Trie to get the longest common prefix.
If the length of the hash table in a certain node does equal to 1 or the symbol of the end of the word exists, return the answer.
Otherwise, we append the current char to the answer and move to the next node.
Last updated
Was this helpful?