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​ 次比较。优化这类情况的一种方法就是水平扫描。我们从前往后枚举字符串的每一列,先比较每个字符串相同列上的字符(即不同字符串相同下标的字符)然后再进行对下一列的比较。

1
2
3
4
5
6
7
8
9
10
11
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   prader6  阅读(103)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)

导航

统计

点击右上角即可分享
微信分享提示