前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Longest Common Prefix

Leetcode: Longest Common Prefix

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 16:03:08
4710
发布2019-01-22 16:03:08
举报
文章被收录于专栏:给永远比拿愉快

题目: Write a function to find the longest common prefix string amongst an array of strings. 即求给定的一组字符串的公共前缀。

思路分析: 一个一个寻找前缀,先比较第一个和第二个,找到公共前缀,然后公共前缀和第三个比较,寻找公共前缀,以此类推。

C++参考代码:

代码语言:javascript
复制
class Solution
{
public:
    string longestCommonPrefix(vector<string> &strs)
    {
        if (strs.empty())
        {
            return "";
        }
        string common = strs[0];
        vector<string>::size_type size = strs.size();
        int length;//保存要比较的两个字符串的最小长度,只在最小长度范围内进行比较
        int count;//记录相等的字符个数
        for (int i = 1; i < size; i++)
        {
            length = min(common.length(), strs[i].length());
            count = 0;
            for (int j = 0; j < length; j++)
            {
                //如果两个字符相等count++
                if (strs[i][j] == common[j])
                {
                    count++;
                }
                //如果两个字符不相等直接退出内层循环
                else
                {
                    break;
                }
            }
            //将common和strs[i]的共同前缀保存在common中,进行下一个字符的比较
            common = common.substr(0, count);
        }
        return common;
    }
};

C#参考代码:

代码语言:javascript
复制
public class Solution
{
    public string LongestCommonPrefix(string[] strs)
    {
        if (strs == null || strs.Length == 0)
        {
            return string.Empty;
        }
        string common = strs[0];
        int length = 0;
        int count = 0;
        for (int i = 1; i < strs.Length; i++)
        {
            length = Math.Min(common.Length, strs[i].Length);
            count = 0;
            for (int j = 0; j < length; j++)
            {
                if (strs[i][j] == common[j])
                {
                    count++;
                }
                else
                {
                    break;
                }
            }
            common = common.Substring(0, count);
        }
        return common;
    }
}

Python参考代码:

代码语言:javascript
复制
class Solution:
    # @return a string
    def longestCommonPrefix(self, strs):
        size = len(strs)
        if not strs or size == 0:
            return ""
        common = strs[0]
        length = 0
        count = 0
        for i in range(1, size):
            length = min(len(common), len(strs[i]))
            count = 0
            for j in range(length):
                if strs[i][j] == common[j]:
                    count += 1
                else:
                    break
            common = common[0: count]
        return common
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015年03月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档