Sharing My 1 ms solution


  • 0
    T
    public String longestCommonPrefix(String[] strs) {
    
        if(strs.length == 1) {
            return strs[0];
        }
    
        int index = -1;
    
        //find the min length string
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < strs.length; i++) {
            String str = strs[i];
            if(str.length() < min) {
                min = str.length();
                index = i;
            }
        }
    
        if(index == -1) {
            return "";
        }
    
        String minLengthString = strs[index];
        char[] charArray = minLengthString.toCharArray();
    
        for (int i = 0; i < strs.length; i++) {
            int j = 0;
            if(i != index) {
                char[] currCharArray = strs[i].toCharArray();
                while(j < min) {
                    if(currCharArray[j] == charArray[j]) {
                        j++;
                        continue;
                    } else {
                        //remove the last character and update min.
                        minLengthString = minLengthString.substring(0, minLengthString.length() - 1);
                        min--;
                    }
                }
            }
        }
    
        return minLengthString;
    }

Log in to reply
 

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