LeetCode之LCP(Longest Common Prefix)问题

原创 2015年07月17日 18:47:01

这个也是简单题目,但是关键在于题意的理解。
题目原文就一句话:Write a function to find the longest common prefix string amongst an array of strings.
题意是给一个字符串数组,找出这个字符串数组中所有字符串的最长公共前缀。
注意是限定的前缀,而不是子串。

所以,直接的解法就是以第一个字符串为基准,逐个比较每个字符。算法复杂度也显然是O(M*N),M是字符串的个数,N是最长前缀的长度。

代码如下:

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        int len = strs.size();
        string prefix;
        if(len == 0)return res;
        for(int pos = 0; pos < strs[0].size(); pos++)//最长前缀的长度不超过strs[0].size(),逐个字符的比较
        {
            // 各个字符串对应位置的字符比较
            for(int k = 1; k < len; k++)
            {
                if(strs[k].size() == pos || strs[k][pos] != strs[0][pos])
                    return res;
            }
            prefix.push_back(strs[0][pos]);
        }
        return prefix;
    }
};

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

Problem: Write a function to find the longest common prefix string amongst an array of strings. ...
  • runningtortoises
  • runningtortoises
  • 2015-05-08 18:40:35
  • 4426

[LeetCode]Longest Common Prefix

题目要求如下: Write a function to find the longest common prefix string amongst an array of strings. 找出所...
  • zhouworld16
  • zhouworld16
  • 2013-11-22 12:37:41
  • 21652

[LeetCode][14]Longest Common Prefix解析 两种算法和底层源码的深入对比-Java实现

Q: Write a function to find the longest common prefix string amongst an array of strings. A: 这题...
  • u014629433
  • u014629433
  • 2016-06-15 13:12:37
  • 2325

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:46
  • 8336

[leetcode:python]14.Longest Common Prefix

题目:最长公共前缀 Write a function to find the longest common prefix string amongst an array of strings. 题...
  • NXHYD
  • NXHYD
  • 2017-05-10 19:07:20
  • 1097

[LeetCode] 014. Longest Common Prefix (Easy) (C++/Java/Python)

[LeetCode] 014. Longest Common Prefix (Easy) (C++/Java/Python)
  • hcbbt
  • hcbbt
  • 2015-03-03 15:34:34
  • 3681

关于LeetCode中Longest Common Prefix一题的理解

题目如下: Write a function to find the longest common prefix string amongst an array of strings.    ...
  • zsy112371
  • zsy112371
  • 2016-09-04 18:33:06
  • 6050

[leetcode]14. Longest Common Prefix -- JavaScript 代码

[leetcode]14. Longest Common Prefix -- JavaScript 代码
  • u014328357
  • u014328357
  • 2016-08-30 11:18:31
  • 532

14. Longest Common Prefix [easy] (Python)

题目链接https://leetcode.com/problems/longest-common-prefix/题目原文 Write a function to find the longest ...
  • coder_orz
  • coder_orz
  • 2016-06-18 17:06:51
  • 4636

Longest Common Prefix -- LeetCode

原题链接: http://oj.leetcode.com/problems/longest-common-prefix/  这道题属于字符串处理的题目,思路比较简单,就是brute force的想法,...
  • linhuanmars
  • linhuanmars
  • 2014-03-18 10:01:31
  • 9551
收藏助手
不良信息举报
您举报文章:LeetCode之LCP(Longest Common Prefix)问题
举报原因:
原因补充:

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