Easy-题目52:14. Longest Common Prefix

原创 2016年05月30日 20:51:02

题目原文:
Write a function to find the longest common prefix string amongst an array of strings.
题目大意:
写一个函数,求出一个字符串数组中所有字符的最长公共前缀。
题目分析:
没什么难的,贪心的一个一个比,直到其中一个字符串比完,或者遇到了不同字符为止。
源码:(language:java)

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0)
            return "";
        else if(strs.length==1)
            return strs[0];
        else
        {
            int sublen=0;
            while(true)
            {
                if(strs[0].length()==0)
                    return "";
                if(sublen==strs[0].length())
                    return strs[0];
                char prefix=strs[0].charAt(sublen);
                for(String str:strs)
                {
                    if(str.length()==sublen || str.charAt(sublen)!=prefix)
                        return str.substring(0,sublen);
                }
                sublen++;
            }
        }
    }
}

成绩:
3ms,beats 40.93%,众数3ms,23.44%

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

LeetCode_Easy心得:14. Longest Common Prefix(C语言)

14. Longest Common Prefix

14. Longest Common Prefix [easy] (Python)

题目链接https://leetcode.com/problems/longest-common-prefix/题目原文 Write a function to find the longest ...

14. Longest Common Prefix

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

LeetCode OJ-14.Longest Common Prefix

LeetCode OJ-14.Longest Common Prefix题目描述 Write a function to find the longest common prefix string...

LeetCode 14 — Longest Common Prefix(C++ Java Python)

题目:http://oj.leetcode.com/problems/longest-common-prefix/ Write a function to find the longest commo...

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

翻译写一个函数(或方法)来寻找一个字符串数组中的最长公共前缀。原文Write a function to find the longest common prefix string amongst a...
  • NoMasp
  • NoMasp
  • 2015-10-16 22:05
  • 5280

LeetCode #14 Longest Common Prefix 最长公共前缀 解题小节

1 题目理解题目的理解就是给定一堆字符串,从中找出最长的公共前缀。前缀是什么?可以理解为一个字符串开头的几个字母,那么公共前缀,就是这一堆字符串开头的前几个(前缀)的最大相同长度是多少。。。就是所有字...

Leetcode_14_Longest Common Prefix

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/40555783 Longest Common Prefix ...

LeetCode之14---Longest Common Prefix

题目:   Write a function to find the longest common prefix string amongst an array of strings. 题目大意:  ...

Leetcode-14. Longest Common Prefix

Problem Description: Write a function to find the longest common prefix string amongst an array of ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)