您的位置:首页 > 其它

Longest Common Prefix

2015-08-01 18:46 295 查看
Write a function to find the longest common prefix string amongst an array of strings.

求解最长公共前缀,看到第一反应是用trie树,简历一颗trie树,然后查找下,某个点的计数次数是不是等于len,不等于则停止,等于则加入公共前缀字符串,继续查找。

class TrieNode {
public:
// Initialize your data structure here.
TrieNode(char v): val(v), count(0){
for(int i = 0; i < 256; ++i)
next[i] = NULL;
}
TrieNode *next[256];
char val;
int count;
};

class Trie {
public:
Trie() {
root = new TrieNode(' ');
}

TrieNode* createNode(char v)
{
TrieNode *newNode = new TrieNode(v);
return newNode;
}

// Inserts a word into the trie.
void insert(string word) {
int len = word.size();
TrieNode *tmpNode = root;
for(int i = 0; i < len; ++i)
{
int tmp = word[i];
if(tmpNode->next[tmp])
{
++tmpNode->next[tmp]->count;
}
else
{
tmpNode->next[tmp] = createNode(word[i]);
++tmpNode->next[tmp]->count;
}

tmpNode = tmpNode->next[tmp];
}
}

string longestCommonPrefix(int number)
{
string ans = "";
TrieNode *tmpNode = root;
while(NULL != tmpNode)
{
int count = 0, index = -1;
for(int i = 0; i < 256; ++i)
{
if(NULL != tmpNode->next[i])
{
++count;
if(count >= 2)
break;
index = i;
}
}
if(tmpNode != root && tmpNode->count == number)
ans.push_back(tmpNode->val);
if(count == 2 || (tmpNode != root && tmpNode->count != number))
break;
else
{
if(count == 0)
break;
tmpNode = tmpNode->next[index];
}
}

return ans;
}

private:
TrieNode* root;
};

class Solution {
public:
//trie树, 构造一颗trie树,然后找到节点count不减少的节点,只要发现减少,
//则说明该节点之前是公共前缀
string longestCommonPrefix(vector<string>& strs) {
int len = strs.size();
string ans = "";
if(len < 1)
return ans;
if(len == 1)
return strs[0];

Trie trie;
for(int i = 0; i < len; ++i)
trie.insert(strs[i]);
return trie.longestCommonPrefix(len);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息