Longest Common Prefix
Find the common prefix in the given strings.
Lets say String [] strs = {"helpinterview","helpquestion","helpcoding"}
Output is
help
because "help' is common prefix.
class LCP
{
public static void main(String ar[])
{
String [] strs = {"helpinterview","helpquestion","helpcoding"};
LCP l = new LCP();
String output = l.findCommonPrefix(strs);
}
public function findCommonPrefix(String [] strs)
{
String prefix = strs[0];
for(int i = 1; i < strs.length; i++)
{
while(strs[i].indexOf(prefix) != 0)
{
prefix = prefix.substring(0,prefix.length() -1 );
if(prefix.isEmpty()) return "";
}
}
return prefix;
}
}