Skip to content

Instantly share code, notes, and snippets.

@AbhiAgarwal192
Created August 21, 2020 05:09
Show Gist options
  • Save AbhiAgarwal192/ca30c99dc3a4c389d985b6fbb228da85 to your computer and use it in GitHub Desktop.
Save AbhiAgarwal192/ca30c99dc3a4c389d985b6fbb228da85 to your computer and use it in GitHub Desktop.
Write a function to find the longest common prefix string amongst an array of strings.
public class TrieNode{
public bool isEndOfWord;
public TrieNode[] children;
public TrieNode(){
isEndOfWord = false;
children = new TrieNode[26];
for(int i=0;i<26;i++){
children[i] = null;
}
}
}
public class Solution {
public TrieNode root;
public void Insert(string str){
TrieNode temp = root;
int len = str.Length;
for(int i=0;i<len;i++)
{
int index = str[i]-'a';
if(temp.children[index] == null){
temp.children[index] = new TrieNode();
}
temp = temp.children[index];
}
temp.isEndOfWord=true;
}
public string GetPrefix(){
if(root == null){
return "";
}
TrieNode temp = root;
string prefix = "";
bool loop = true;
while(loop && !temp.isEndOfWord){
TrieNode found = null;
int index = 0;
for(int i=0;i<26;i++){
if(temp.children[i]!=null){
if(found == null){
found = temp.children[i];
index = i;
}
else{
loop = false;
}
}
}
if(loop){
prefix = prefix + (Convert.ToChar(index+'a')).ToString();
}
temp = found;
}
return prefix;
}
public string LongestCommonPrefix(string[] strs) {
root = new TrieNode();
int len = strs.Length;
if(len==0){
return "";
}
for(int i=0;i<len;i++){
Insert(strs[i]);
}
string prefix = GetPrefix();
return prefix;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment