【Leetcode】14. 最长公共前缀

leetcode原地址:https://leetcode.cn/problems/longest-common-prefix

描述

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

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

示例 1:

输入:strs = [“flower”,“flow”,“flight”]
输出:“fl”
示例 2:

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

提示:

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

题解

    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        int length = strs[0].length();
        int count = strs.length;
        for (int i = 0; i < length; i++) {
            char c = strs[0].charAt(i);
            for (int j = 1; j < count; j++) {
                if (i == strs[j].length() || strs[j].charAt(i) != c) {
                    return strs[0].substring(0, i);
                }
            }
        }
        return strs[0];
    }

相关推荐

  1. LeetCode 14 公共前缀

    2024-07-19 17:50:04       62 阅读
  2. leetCode算法—14. 公共前缀

    2024-07-19 17:50:04       61 阅读
  3. LeetCode 14. 公共前缀

    2024-07-19 17:50:04       30 阅读
  4. Leetcode 14. 公共前缀

    2024-07-19 17:50:04       26 阅读
  5. Leetcode14. 公共前缀

    2024-07-19 17:50:04       18 阅读
  6. 14.公共前缀

    2024-07-19 17:50:04       22 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-19 17:50:04       70 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-19 17:50:04       74 阅读
  3. 在Django里面运行非项目文件

    2024-07-19 17:50:04       62 阅读
  4. Python语言-面向对象

    2024-07-19 17:50:04       72 阅读

热门阅读

  1. 从零开始!Jupyter Notebook 安装教程

    2024-07-19 17:50:04       22 阅读
  2. iptables

    iptables

    2024-07-19 17:50:04      21 阅读
  3. MATLAB6:M文件和控制流

    2024-07-19 17:50:04       20 阅读
  4. early-stopping pytorch refs

    2024-07-19 17:50:04       20 阅读
  5. C++案例三:猜数字游戏

    2024-07-19 17:50:04       19 阅读
  6. 构建高可用应用的设计模式与实践

    2024-07-19 17:50:04       18 阅读
  7. MySQL简介

    2024-07-19 17:50:04       15 阅读