码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 14. 最长公共前缀(Longest Common Prefix)

时间:2019-05-25 17:04:40      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:str   pre   pil   public   flow   mon   ==   返回   资料   

14. 最长公共前缀
14. Longest Common Prefix

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

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

LeetCode14. Longest Common Prefix

示例 1:

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

示例 2:

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

说明:
所有输入只包含小写字母 a-z。

Java 实现

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String pre = strs[0];
        int i = 1;
        while (i < strs.length) {
            while (strs[i].indexOf(pre) != 0) {
                pre = pre.substring(0, pre.length() - 1);
            }
            i++;
        }
        return pre;
    }
}

参考资料

LeetCode 14. 最长公共前缀(Longest Common Prefix)

标签:str   pre   pil   public   flow   mon   ==   返回   资料   

原文地址:https://www.cnblogs.com/hglibin/p/10922889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!