Given a list of strings that may or many not have a common prefix, we wan to find the longest common prefix.
Example:
Input = { “Hospital”, “Host”, “Hostage”}
Ans: Hos
Solution:
We can use the “StartsWith” string function to make our lives easier.
Basically we will make initial assumption and make the first string as a common prefix.
We then iterate through each string (1,2…) starting from index 1 and check if it starts with our string at 0 index (common prefix)
If it doesn't start with it, then we will remove one char from the end of the common prefix and keep checking until it does.
public string LongestCommonPrefix(string[] strs) {
string common = strs[0];
for(int i=1; i < strs.Length; i++) {
while(!strs[i].StartsWith(common)) {
common = common.Substring(0, common.Length-1);
}
}
return common;
}