Longest Common Prefix

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)