每天一道面试题-最长公共前缀

每天一道面试题-最长公共前缀

leetcode(简单):14. 最长公共前缀

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

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

示例 1:

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

示例 2:

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

纵向扫描

纵向扫描时,从前往后遍历所有字符串的每一列,比较相同列上的字符是否相同,如果相同则继续对下一列进行比较,如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀。

fig2

代码如下:

package cn.lbl.face.leetCode;

public class 最长公共前缀3 {
    
    

    //这个是使用了纵向比较的方法
        public static String longestCommonPrefix(String[] strs) {
    
    
            //如果trs字符数组为空或长度为0,则没有公共前缀,返回""
            if (strs == null || strs.length == 0) {
    
    
                return "";
            }

            //获取strs数组中第一个字符串的长度
            int length = strs[0].length();
            //获取strs字符串数组的长度,即字符串个数
            int count = strs.length;
            //循环判断条件,length,即strs数组中第一个字符串的长度
            for (int i = 0; i < length; i++) {
    
    
                //获取strs数组中第一个字符串的第i个字符
                char c = strs[0].charAt(i);
                //遍历strs中除第一个字符串的其他字符串
                for (int j = 1; j < count; j++) {
    
    
                    //1.判断strs中第j个字符串的长度是否是i相等
                    //2.判断strs中第j个字符串的第i个字符是否和c相等
                    if (i == strs[j].length() || strs[j].charAt(i) != c) {
    
    
                        //如果相等,当截取0到(i-1)个字符,然后返回
                        return strs[0].substring(0, i);
                    }
                }
            }
            //如果循环中没有返回,则说明都相等,所以返回自己
            return strs[0];
        }

    public static void main(String[] args) {
    
    
        String[] strings = new String[]{
    
    "flower","flow","flight"};
        System.out.println(longestCommonPrefix(strings));
    }
    }

复杂度分析:

时间复杂度:O(mn),其中 mmm 是字符串数组中的字符串的平均长度,nnn 是字符串的数量。最坏情况下,字符串数组中的每个字符串的每个字符都会被比较一次。
空间复杂度:O(1)。使用的额外空间复杂度为常数。

猜你喜欢

转载自blog.csdn.net/qq_37924905/article/details/108522683