This is a solution that I came up with
struct node {
map<char, node*> next;
};
node * root = new node();
void insert(string s, node* root) {
node * temp = root;
for(int i=0;i<s.size();i++) {
if(temp->next.find(s[i]) != temp->next.end()) {
// char exists
temp = temp->next[s[i]];
} else {
temp->next[s[i]] = new node();
temp = temp->next[s[i]];
}
}
}
string findLongestCommonPrefix(node* root) {
node * temp = root;
string res = "";
while(temp->next.size()==1) {
res += temp->next.begin()->first;
temp = temp->next.begin()->second;
}
return res;
}
string Solution::longestCommonPrefix(vector<string> &A) {
for(int i=0;i<A.size();i++) {
insert(A[i], root);
}
return findLongestCommonPrefix(root);
}
and for the input
A : [ "abcd", "abde", "abcf" ]
my code returns
ab
when I test it as custom input. But the same code returns an empty string when using the Test button.
Can someone help me?