arts lettcode title

Write a function to find the longest common prefix string array.

If there is no common prefix, it returns an empty string "."

Example 1:

Input: [ "flower", "flow ", "flight"]
Output: "fl"
Example 2:

Input: [ "dog", "racecar ", "car"]
Output: ""
Explanation: there is no input common prefix.
Description:

All input contains only lowercase letters az.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/longest-common-prefix
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

public static   String get(String[] strs){
        if (strs.length == 0){
            return "";
        }
        if (strs.length == 1){
            return strs[0];
        }
        String longs = "";
        HashMap<Integer, String> firstMap = new HashMap<>();

        HashMap<Integer, String> secondMap = new HashMap<>();
        String s = strs[0];
        String[] split = s.split("");
        for (int i = 0; i < split.length; i++){
            firstMap.put(i, split[i]);
        }
        for (int i = 1; i < strs.length; i++){
            String string = strs[i];
            String[] split1 = string.split("");
            HashMap<Integer, String> tempMap = new HashMap<>();
            for (int j = 0; j < split1.length; j++){
                if (firstMap.size() < j+1){
                    continue;
                }
                if (firstMap.get(j).equals(split1[j])){
                    tempMap.put(j,split1[j]);
                   continue;
                }else {
                    break;
                }
            }
            firstMap = tempMap;
            if (i == strs.length -1){
                secondMap = tempMap;
            }
        }
        if (secondMap.size() == 0){
            return "";
        }
        for (int i = 0; i < secondMap.size(); i++){
            longs += secondMap.get(i);
        }
        return longs;
    }

Official problem-solving:

algorithm

Imagine the end of the array has a very short string, using the above method will still be S S comparisons. A method of optimizing such cases is the horizontal scanning. Each column from front to back us enumerate strings, each string comparison of the first column of the same character (that is the subject of the same character at different string) and then compare the next column.

public String longestCommonPrefix(String[] strs) {
    if (strs == null || strs.length == 0) return "";
    for (int i = 0; i < strs[0].length() ; i++){
        char c = strs[0].charAt(i);
        for (int j = 1; j < strs.length; j ++) {
            if (i == strs[j].length() || strs[j].charAt(i) != c)
                return strs[0].substring(0, i);             
        }
    }
    return strs[0];
}

  The first to do it yourself. .

Guess you like

Origin www.cnblogs.com/prader6/p/12081530.html