【d33】【Java】【力扣】14. 最长公共前缀

题目

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

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

示例 1:

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

示例 2:

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

提示:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] 仅由小写英文字母组成

思路

遍历第一个字符串,循环变量为i

依次判断 后面每一个字符串的第i个字符是否=第一个字符串的第i个字符

注意:为了避免越界,i为最短的字符串的长度

代码

public class Main {
    public static void main(String[] args) {
        String[] strs = {"cir", "car"};
        System.out.println(longestCommonPrefix(strs));

    }

    public static String longestCommonPrefix(String[] strs) {
        //获取最小的元素长度
        int min = strs[0].length();
        for (String a :
                strs) {
            if (a.length() < min) {
                min = a.length();
            }
        }
        String result = "";
        if (strs.length >= 2) {
            for (int i = 0; i < min; i++) {
                boolean ifStop = false;
                for (int j = 1; j < strs.length; j++) {
                    //第j个元素的第i个字符是否和temp相等
                    if (strs[j].charAt(i) == strs[0].charAt(i))
                        continue;
                    else {
                        ifStop = true;//是否因为某一列上的不满足而终止
                        break;
                    }
                }
                if (ifStop)
                    break;
                else result=result+String.valueOf(strs[0].charAt(i));;
            }
        } else if (strs.length == 1) result = strs[0];
        else result = "";
        return result;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值