0014. Longest Common Prefix
Easy | String + Trie | 16 ms (94.87%), 13.7 MB (39.95%)
Last updated
Was this helpful?
Easy | String + Trie | 16 ms (94.87%), 13.7 MB (39.95%)
Last updated
Was this helpful?
Source: GitHub:
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 ""
.
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.