JAVA Solution, Beat 83.49%


  • 0
    J

    We can first find the most short string in the array,It will save many time.

    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if (strs == null || strs.length < 1) return "";
            if (strs.length == 1) return strs[0];
            int len = strs.length, index = 0, min = Integer.MAX_VALUE;
            for (int i = 0; i < len; i++) {
                int l = strs[i].length();
                if (l < min) {
                    min = l;
                    index = i;
                }
            }
            
            for (int i = min; i > 0; i--) {
                String target = strs[index].substring(0, i);
                int j = 0;
                for (; j < len; j++) {
                    if (strs[j].indexOf(target) != 0) {
                        break;
                    }
                }
                if (j == len) return target;
            }
    
    
    
            
            return "";
        }
    }

Log in to reply
 

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