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

Longest Common Prefix

时间:2015-05-12 09:37:20      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
    	if(strs.size()==0) return "";
    	string cmp = strs[0];
    	for(size_t i=1;i!=strs.size();++i){
    		cmp = compare(cmp,strs[i]);
    		if(cmp.size()==0) return "";
    	}
    	return cmp;
    }
private:
    string compare(string &str1,string &str2){
    	string res;
    	for(size_t i=0;i!=str1.size()&&i!=str2.size();++i){
    		if(str1[i]==str2[i]){
    			res += str1[i];
    		}else{
    		    break;
    		}
    	}
    	return res;
    }
};


Longest Common Prefix

标签:

原文地址:http://blog.csdn.net/guorudi/article/details/45648833

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