leetcode

Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

Compare all the char in the first string with the rest of the strings in the array. If the length of the string is less than the processing string, return or if the char in the string is not equal to the processing string, return.

public String longestCommonPrefix(String[] strs) {
        if (strs==null||strs.length==0) {
            return "";
        }

        if (strs.length==1) {
            return strs[0];
        }

        StringBuilder result = new StringBuilder();
        int index = 0;
        while (index<strs[0].length()) {
            for (int i=1; i<strs.length; i++) {
                if (strs[i].length()<=index) {
                    return result.toString();
                }               
                if (strs[i].charAt(index)!=strs[0].charAt(index)) {
                    return result.toString();
                }           
            }
            result.append(strs[0].charAt(index));
            index++;
        }
        return result.toString();
    }