prader6

arts lettcode 题目

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"
示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:

所有输入只包含小写字母 a-z 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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;
    }

官方解题:

算法

想象数组的末尾有一个非常短的字符串,使用上述方法依旧会进行 S​S​ 次比较。优化这类情况的一种方法就是水平扫描。我们从前往后枚举字符串的每一列,先比较每个字符串相同列上的字符(即不同字符串相同下标的字符)然后再进行对下一列的比较。

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];
}

  第一次自己做出来。。

posted on 2019-12-22 22:47  prader6  阅读(100)  评论(0编辑  收藏  举报

导航