首页 > 其他分享 >leetcode 14. 最长公共前缀

leetcode 14. 最长公共前缀

时间:2023-02-25 14:46:23浏览次数:39  
标签:return 前缀 strs mid int length 14 leetcode String

直接法

直接法又分为竖向扫描和横向扫描,以下的这种方式就是竖向扫描

class Solution {
    public String longestCommonPrefix(String[] strs) {
        StringBuilder commonPrefix = new StringBuilder();
        if (strs == null) {
            return null;
        }
        if (strs.length <= 1) {
            return strs[0];
        }
        int len = strs.length;
        for (int i = 0; i < strs[0].length(); i++) {
            commonPrefix.append(strs[0].charAt(i));
            for (int j = 1; j < len; j++) {
                if (strs[j].length() < commonPrefix.length() || !strs[j].startsWith(commonPrefix.toString())) {
                    commonPrefix.deleteCharAt(i);
                    return commonPrefix.toString();
                }
            }
        }
        return commonPrefix.toString();
    }
}

分治法

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        } else {
            return longestCommonPrefix(strs, 0, strs.length - 1);
        }
    }

    public String longestCommonPrefix(String[] strs, int start, int end) {
        if (start == end) {
            return strs[start];
        } else {
            int mid = (end - start) / 2 + start;
            String lcpLeft = longestCommonPrefix(strs, start, mid);
            String lcpRight = longestCommonPrefix(strs, mid + 1, end);
            return commonPrefix(lcpLeft, lcpRight);
        }
    }

    public String commonPrefix(String lcpLeft, String lcpRight) {
        int minLength = Math.min(lcpLeft.length(), lcpRight.length());       
        for (int i = 0; i < minLength; i++) {
            if (lcpLeft.charAt(i) != lcpRight.charAt(i)) {
                return lcpLeft.substring(0, i);
            }
        }
        return lcpLeft.substring(0, minLength);
    }
}

二分查找

显然,最长公共前缀的长度不会超过字符串数组中的最短字符串的长度。用
minLength 表示字符串数组中的最短字符串的长度,则可以在
[0,minLength] 的范围内通过二分查找得到最长公共前缀的长度。每次取查找范围的中间值
mid,判断每个字符串的长度为
mid 的前缀是否相同,如果相同则最长公共前缀的长度一定大于或等于
mid,如果不相同则最长公共前缀的长度一定小于
mid,通过上述方式将查找范围缩小一半,直到得到最长公共前缀的长度。

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        int minLength = Integer.MAX_VALUE;
        for (String str : strs) {
            minLength = Math.min(minLength, str.length());
        }
        int low = 0, high = minLength;
        while (low < high) {
            int mid = (high - low + 1) / 2 + low;
            if (isCommonPrefix(strs, mid)) {
                low = mid;
            } else {
                high = mid - 1;
            }
        }
        return strs[0].substring(0, low);
    }

    public boolean isCommonPrefix(String[] strs, int length) {
        String str0 = strs[0].substring(0, length);
        int count = strs.length;
        for (int i = 1; i < count; i++) {
            String str = strs[i];
            for (int j = 0; j < length; j++) {
                if (str0.charAt(j) != str.charAt(j)) {
                    return false;
                }
            }   
        }
        return true;
    }
}

标签:return,前缀,strs,mid,int,length,14,leetcode,String
From: https://www.cnblogs.com/jrjewljs/p/17154373.html

相关文章

  • [LeetCode] 1332. Remove Palindromic Subsequences 删除回文子序列
    Youaregivenastring s consisting only ofletters 'a' and 'b'.Inasinglestepyoucanremoveone palindromicsubsequence from s.Return the mi......
  • vue.js代码014
    <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title><scripttype="text/javascript"src="../js/vue.js"></script></head><......
  • 洛谷P1149
    [洛谷P1149]([P1149NOIP2008提高组]火柴棒等式-洛谷|计算机科学教育新生态(luogu.com.cn))publicclassP1149{ publicstaticvoidmain(String[]args){ S......
  • [LeetCode] 1247. Minimum Swaps to Make Strings Equal
    Youaregiventwostrings s1 and s2 ofequallengthconsistingofletters "x" and "y" only.Yourtaskistomakethesetwostringsequaltoeachother.......
  • LeetCode 64. 最小路径和
    原题解题目约束题解classSolution{public:intminPathSum(vector<vector<int>>&grid){if(grid.size()==0||grid[0].size()==0){......
  • LeetCode 62. 不同路径(/)
    题目约束题解解法一classSolution{public:intuniquePaths(intm,intn){vector<vector<int>>f(m,vector<int>(n));for(inti=......
  • 14.配置中心
    加载配置会优先加载配置中心里的,其次才是加载配置文件里的导入依赖下载并启动NacosServer前面注册中心已经弄过了,配置中心也是用的nacos,所以这一步不需要弄了下载测......
  • #yyds干货盘点# LeetCode程序员面试金典:最小差
    题目:给定两个整数数组a和b,计算具有最小差绝对值的一对数值(每个数组中取一个值),并返回该对数值的差 示例:输入:{1,3,15,11,2},{23,127,235,19,8}输出:3,即数值对(11,8)......
  • #yyds干货盘点# LeetCode程序员面试金典:最大数值
    题目:编写一个方法,找出两个数字​​a​​​和​​b​​中最大的那一个。不得使用if-else或其他比较运算符。示例:输入:a=1,b=2输出:2代码实现:classSolution{public......
  • #yyds干货盘点# LeetCode面试题:K 个一组翻转链表
    1.简述:给你链表的头节点head,每 k 个节点一组进行翻转,请你返回修改后的链表。k是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩......