您的位置:首页 > 其它

Leetcode 14. Longest Common Prefix

2018-01-29 14:07 274 查看
原题:

Write a function to find the longest common prefix string amongst an array of strings.

解决方法:

算是比较简单的一道题,在这里我使用了Trie的方法。从该题本身来说,使用Trie并没有提升多少性能。但做为字符串字典的大招Trie,其掌握熟练与否是有重大意义的,从这道题开始我们就尝试着用Trie来解决字符串的字典问题吧。

代码:
string longestCommonPrefix(vector<string>& strs) {
struct TrieNode{
TrieNode* next[256] = {0};
int count = 0;
bool isWord = false;
};

int n = strs.size();
if (n < 1)
return "";
else if (n == 1)
return strs[0];

TrieNode* root = new TrieNode;

for(auto str: strs){
TrieNode* cur = root;
for(auto ch: str){
if (!cur->next[ch]){
cur->next[ch] = new TrieNode;
cur->count++;
}
cur = cur->next[ch];
}

if (cur)
cur->isWord = true;
}

int longest = 0;
TrieNode* cur = root;
while(cur && cur->count == 1 && !cur->isWord){
++longest;
for(int i = 0; i < 256;i++){
if (cur->next[i]){
cur = cur->next[i];
break;
}
}
}

return longest > 0 ? strs[0].substr(0, longest) : "";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Leetcode C Trie