Two methods,one is 3ms and another is 5ms for java


  • 0
    C

    There are two methods for this problem.
    One method is compare prefix with the next string start the first string. This method spend 5ms. It beats 14.22% of java submissions.
    Another method is compare the first char with the first char of the next string from the first string.This method spend 3ms.It beats 45.43% of java submissions.

    Method 1:
    public String longestCommonPrefix(String[] strs) {

        if(strs==null||strs.length==0)
            return "";
        String prefix=strs[0];
        for(int i=1;i<strs.length;i++){
            int j=0;
            while(j<strs[i].length()&&j<prefix.length()&&strs[i].charAt(j)==prefix.charAt(j))
                j++;
            prefix=prefix.substring(0,j);
        }
        return prefix;
    }
    

    Method 2:

        public String longestCommonPrefix(String[] strs) {
    
        if(strs==null||strs.length==0)
            return "";
        if(strs[0].length()==0)
            return "";
        String prefix="";
        for(int i=0;i<strs[0].length();i++){
            char temp=strs[0].charAt(i);
            int j=1;
            while(j<strs.length&&i<strs[j].length()&&temp==strs[j].charAt(i))
                j++;
            if(j!=strs.length)
                return prefix;
            prefix=strs[0].substring(0,i+1);
        }
        return prefix;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.