Java solution


  • 0
    L
        public String longestCommonPrefix(String[] strs) {
            if(strs==null || strs.length==0) {
                return "";
            }
            if(strs.length==1) {
                return strs[0];
            }
            
            //find the smallest string.
            //time complexity is O(n*k)
            String smallest="";
            int len = Integer.MAX_VALUE;
            for(String s : strs) {
                if(len>s.length()) {
                    len = s.length();
                    smallest = s;
                }
            }
            
            //time complexity is O(n*k)
            StringBuilder builder = new StringBuilder();
            for(int i=0;i<smallest.length();i++) {
             for(String s : strs) {
                if(s==smallest) {
                    continue;
                }            
                if(s.charAt(i)!=smallest.charAt(i)) {
                    return builder.toString();
                }
              }
              builder.append(smallest.charAt(i));
            }
            
            return builder.toString();
        }
    

Log in to reply
 

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