In two strings:
\"Mary Had a Little Lamb\"
\"Mary Had a Big Lamb\"
should return
\"Mary Had a \"
A very not efficient and probably might be criticised a lot. But i came up with this idea and surprisingly it satisfied all of my test cases. And it even did the work that you were intending to do. Easy to understand. Please do comment on it and let me know how i can improve it. (open to all kinds of remarks and improvement)
class Solution {
public String longestCommonPrefix(String[] strs) {
int i;
StringBuilder sb = new StringBuilder("");
if(strs.length == 0 ){
return sb.toString();
}
for(int j = 0 ; j< strs[0].length();j++)
{
int count=0;
for(String word: strs){
try{
word.charAt(j);
}catch(Exception e){
return sb.toString();
}
if(word.charAt(j) == strs[0].charAt(j) ){
count ++;
}else{
return sb.toString();
}
if(count == strs.length){
sb.append(word.charAt(j));
}
}
}
return sb.toString();
}}