leetcode学习笔记14 Longest Common Prefix

leetcode学习笔记14

问题

lLongest Common Prefix

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

If there is no common prefix, return an empty string “”.

Example 1:

Input: strs = [“flower”,“flow”,“flight”]
Output: “fl”

Example 2:

Input: strs = [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.

Constraints:

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lower-case English letters.

思考

最长的共同前缀,所以每个字符从头开始匹配看是不是相同就好了.

方法1

假设最短字符长度为n, 每个字符都只需要最多检查到第n位就可以了.或者直接把最短长度的字符作为起始, 开始遍历.

时间复杂度 O ( M ∗ N ) O(M * N) O(MN).
空间复杂度 O ( N ) O(N) O(N).

M:字符串个数
N:最短字符串长度

class Solution {
    public String longestCommonPrefix(String[] strs) {
        int len = 201;
        String res = "";
        // 找到最小的len, 以及对应的str
        for(String str : strs){
            if(str.length() < len){
                len = str.length();
                res = str;
            }
        }
        
        for(String str : strs){
            for(int i = 0; i < len; i++){
                if(str.charAt(i) != res.charAt(i)){
                    len = i;
                    res = res.substring(0, len);
                    break;
                }
            }
        }
        
        return res;
    }
}

方法2

方法1是按照字符串来进行遍历.也可以按照位数来进行遍历.
共同前缀, 也就是说如果存在,那么所有的字符串的一定是从第一个字符开始有相同的部分.那么就从第一个字符开始遍历,直到碰到不相同的,或者是长度不够的字符为止.

时间复杂度其实和方法一样,不过省去了很多string的操作.在极大量数据的时候估计会有性能提升.

时间复杂度 O ( M ∗ N ) O(M * N) O(MN).
空间复杂度 O ( N ) O(N) O(N).

M:字符串个数
N:最短字符串长度

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length == 0)
            return "";
        
        String f = strs[0];
        for(int i = 0, len = f.length();i < len; i++){
            char c = f.charAt(i);
            for(int j = 0; j < strs.length; j++){
                if(i >= strs[j].length() || c != strs[j].charAt(i)){
                    return f.substring(0, i);
                }
            }
        }
        return f;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值