首页 > 其他 > 详细

Longest Common Prefix

时间:2014-11-14 23:57:48      阅读:518      评论:0      收藏:0      [点我收藏+]

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

(每个字符串从0开始的公共部分即最长公共前缀)

C++代码如下:

#include<iostream>
#include<string>
#include<vector>
using namespace std;

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        if(strs.empty())
            return "";
        string s1=strs[0];
        string s2;
        size_t len=s1.size();
        for(size_t i=1;i<strs.size();i++)
        {
            s2=strs[i];
            if(s2.size()<len)
                len=s2.size();
            for(size_t j=0;j<len;j++)
            {
                if(s1[j]!=s2[j])
                {
                    len=j;
                    break;
                }
            }
        }
        return s1.substr(0,len);
    }
};

int main()
{
    vector<string> vec={"aaaaai","aaaaa","aaaa","aaab","aaaagg"};
    Solution s;
    cout<<s.longestCommonPrefix(vec)<<endl;
}

运行结果:

bubuko.com,布布扣

Longest Common Prefix

原文:http://www.cnblogs.com/wuchanming/p/4098307.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!