Created
August 21, 2020 05:09
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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