Find longest common prefix?

前端 未结 9 1883
忘掉有多难
忘掉有多难 2020-12-10 03:50

In two strings:

\"Mary Had a Little Lamb\"
\"Mary Had a Big Lamb\"

should return

\"Mary Had a \"

9条回答
  •  Happy的楠姐
    2020-12-10 04:09

    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();
    }}
    

提交回复
热议问题