My 1ms java solution


  • 0
    L
    public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0) return "";
        int shortestIndex=0;
        int shortestLen=strs[0].length();
        for(int i=0;i<strs.length;i++){
            if(strs[i].length()<shortestLen){
                shortestLen=strs[i].length();
                shortestIndex=i;
            }
        }
        while(shortestLen>0){
            int i=0;
            for(i=0;i<strs.length&&strs[i].startsWith(strs[shortestIndex].substring(0,shortestLen));i++);
            if(i==strs.length) return strs[shortestIndex].substring(0,shortestLen);
            shortestLen--;
        }
        return "";
    }
    

    }


  • 0
    X

    It seems that I underestimated the efficiency of Java API startsWith() and substring(). I firstly tried to avoid using them and got 2ms solution but couldn't see where to improve. Thanks guys.


Log in to reply
 

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