力扣14. 最长公共前缀

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

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

示例 1:

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

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

class Solution {
    public String longestCommonPrefix(String[] strs) {
        int n = strs.length;String result = "";
        if(n == 0) return "";
        if(n < 2) return strs[0];
        int len = strs[0].length();
        for(int i = 0 ; i < len;i++){
            char s = strs[0].charAt(i);
            for(int j = 1;j < n;j++){
                if(strs[j].length() <= i || strs[j].charAt(i) != s){
                    return result;
                }
            }
            result += s;
        }
        return result;
    }
}
全部评论

相关推荐

身边有人上海、深圳&nbsp;6、7k&nbsp;都去了,真就带薪上班了。
小浪_coder:深圳除了一些计算机,UI设计,金融类等一些可以月薪过万的工作之外, 认识很多朋友做运营,营销,文员的工作, 月薪基本都在4-6K左右,还有大把人在干
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务