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

14. Longest Common Prefix

时间:2017-07-17 21:46:42      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:div   efi   prefix   pre   write   long   longest   cto   amp   

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

 

找出,给出的一堆字符串的公共前缀。两个两个比较

class Solution {
public:
    string getcom(string &a,string &b) {
        int m = min(a.size(), b.size());
        string t = "";
        for (int i = 0; i < m; ++i) {
            if (a[i] != b[i]) return t; 
            else t += a[i];
        }
        return t;
    }
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.size() == 0) return "";
        string s = strs[0];
        for (int i = 1; i < strs.size(); ++i) {
            s = getcom(s, strs[i]); 
        }
        //cout<<s<<endl;
        return s;
    }
};

 

14. Longest Common Prefix

标签:div   efi   prefix   pre   write   long   longest   cto   amp   

原文地址:http://www.cnblogs.com/pk28/p/7197311.html

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