资讯专栏INFORMATION COLUMN

[LeetCode] Longest Common Prefix

ivan_qhz / 1599人阅读

摘要:我的思路是用对中的字符串逐个遍历第位的字符,如果都相同,就把这个字符存入,否则返回已有的字符串。注意,第二层循环的条件的值不能大于。

Problem

Write a function to find the longest common prefix string amongst an array of strings.

Note

我的思路是用StringBuilderstrs中的字符串逐个遍历第i位的字符,如果都相同,就把这个字符存入sb,否则返回已有的sb字符串。
注意,第二层for循环的条件:i的值不能大于str.length()-1

Solution
class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) return "";
        int len = strs[0].length();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            for (String str: strs) {
                if (str.length() < i+1 || str.charAt(i) != strs[0].charAt(i)) {
                    return sb.toString();
                }
            }
            sb.append(strs[0].charAt(i));
        }
        return sb.toString();
    }
}
Update 2018-8
class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) return "";
        Arrays.sort(strs);
        //compare strs[0] and strs[strs.length-1], since they should be the most different pair
        int i = 0, len = strs.length;
        while (i < Math.min(strs[0].length(), strs[len-1].length()) && strs[0].charAt(i) == strs[len-1].charAt(i)) {
            i++;
        }
        return strs[0].substring(0, i);
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64779.html

相关文章

  • LeetCode Easy】014 Longest Common Prefix

    摘要:注意要检查参数数组是否为空或循环找出数组中最短的那个单词,以这个单词为基准,两层循环嵌套,外层是遍历这个最短单词的每一个字母,内层是遍历所有单词,看其它单词这个位置的字母是否和最短单词一样,若都一样,继续向下遍历,若有不一样的,,返回当前的 Easy 014 Longest Common Prefix Description: find the longest common prefi...

    BDEEFE 评论0 收藏0
  • # Leetcode 14:Longest Common Prefix 最长公共前缀

    摘要:公众号爱写编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串。由于字符串长度不一,可以先遍历找出最小长度字符串,这里我选择抛错的形式,减少一次遍历。 公众号:爱写bug Write a function to find the longest common prefix string amongst an array of strings. If there...

    Keagan 评论0 收藏0
  • # Leetcode 14:Longest Common Prefix 最长公共前缀

    摘要:公众号爱写编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串。由于字符串长度不一,可以先遍历找出最小长度字符串,这里我选择抛错的形式,减少一次遍历。 公众号:爱写bug Write a function to find the longest common prefix string amongst an array of strings. If there...

    FrancisSoung 评论0 收藏0
  • leetcode 14 Longest Common Prefix

    摘要:题目详情题目要求是,给定一个字符串的数组,我们要找到所有字符串所共有的最长的前缀。为了解决这个问题,可以每次都纵向对比每一个字符串相同位置的字符,找出最长的前缀。 题目详情 Write a function to find the longest common prefix string amongst an array of strings. 题目要求是,给定一个字符串的数组,我们要...

    suosuopuo 评论0 收藏0
  • leetcode 14 Longest Common Prefix

    摘要:题目详情题目要求是,给定一个字符串的数组,我们要找到所有字符串所共有的最长的前缀。为了解决这个问题,可以每次都纵向对比每一个字符串相同位置的字符,找出最长的前缀。 题目详情 Write a function to find the longest common prefix string amongst an array of strings. 题目要求是,给定一个字符串的数组,我们要...

    jackwang 评论0 收藏0

发表评论

0条评论

ivan_qhz

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<