美文网首页
最长公共前缀

最长公共前缀

作者: 二进制的二哈 | 来源:发表于2019-11-29 11:43 被阅读0次

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix

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

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

示例 1:

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

示例 2:

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

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

Java代码:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length == 1)
            return strs[0];
        if(strs.length > 0){
            StringBuffer sb = new StringBuffer();
            int index = 0;
            char tmp = ' ';
            while(true){
                for(int i = 0;i<strs.length;i++){
                    String s = strs[i];
                    if(s.length() <= index)
                        return sb.toString();
                    if(tmp == ' '){
                        tmp = s.charAt(index);
                    }else{
                        if(tmp !=s.charAt(index))
                            return sb.toString();
                    }
                }
                sb.append(strs[0].charAt(index));
                tmp = ' ';
                index++;
            }
        }
        return "";
    }
}

相关文章

  • LeetCode 每日一题 [19] 最长公共前缀

    LeetCode 最长公共前缀 [简单] 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回...

  • 14. 最长公共前缀

    20180923-摘抄自14. 最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,...

  • 5,最长公共前缀/数组与字符串

    最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例 1:...

  • Swift 最长公共前缀 - LeetCode

    题目: 最长公共前缀 描述: 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""...

  • leetcode探索之旅(14)

    最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。 示例 1: ...

  • Leetcode 14 最长公共前缀

    最长公共前缀 题目 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例...

  • LeetCodeSwift 14.Longest Common

    题目 最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例...

  • [day4] [LeetCode] [title14,122]

    14.最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串""。 示例 ...

  • 14. 最长公共前缀

    14. 最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。 说明...

  • leetcode算法-最长公共前缀

    最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。 说明:所有输...

网友评论

      本文标题:最长公共前缀

      本文链接:https://www.haomeiwen.com/subject/hlgwwctx.html