码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode(14)Longest Common Prefix

时间:2015-08-06 17:02:30      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

题目

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

分析

该题目是求一个字符串容器中所有字符串的最长公共前缀。

AC代码

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.size() == 0)
            return "";
        else if (strs.size() == 1)
            return *(strs.begin());

        vector<string>::iterator beg, end;
        beg = strs.begin();

        //先得到前两个串的公共前缀
        string str = CommonPrefix(*beg, *(beg+1));

        //迭代器后移两个位置
        beg += 2;

        while (beg != strs.end())
        {
            if (str == "")
                break;
            str = CommonPrefix(str, *(beg++));
        }

        return str;
    }

    string CommonPrefix(const string &str1, const string &str2)
    {
        string common = "";
        if (str1 == "" || str2 == "")
            return common;

        int len1 = strlen(str1.c_str()) , len2 = strlen(str2.c_str());

        int len = len1 > len2 ? len2 : len1 ;

        for (int i = 0; i < len; i++)
        {
            if (str1[i] == str2[i])
                common += str1[i];
            else
                break;
        }

        return common;
    }
};

GitHub测试程序代码

LeetCode(14)Longest Common Prefix

标签:

原文地址:http://blog.csdn.net/fly_yr/article/details/47317429

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!