Java Code - Simple

  • 0
    public String longestCommonPrefix(String[] strs) {
            if(strs==null||strs.length==0) return "";
            if(strs.length==1)return strs[0];
            int minLen = Integer.MAX_VALUE;
            String shortest = null;
      //To find the shortest string
            for(String str:strs){
                    minLen = str.length();
                    shortest = str;
    //Comparing each character of all the strings with the shortest one
            for(int i=0;i<shortest.length();i++){
                char ch = shortest.charAt(i);
                for(String str:strs){
                        return shortest.substring(0,i);
            return shortest;

Log in to reply

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