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

Longest Common Prefix

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

标签:style   blog   http   io   color   ar   os   sp   for   

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

标签:style   blog   http   io   color   ar   os   sp   for   

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

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