首页 > 代码库 > LeetCode 014 Longest Common Prefix

LeetCode 014 Longest Common Prefix

【题目】


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


【题意】

求一组字符串的最长公共前缀


【思路】

使用归并思想求解
要求字符串[1,2,..,k,k+1,...n]的最大公共前缀,先分别求[1,2,...k]和[k+1,...,n]的公共前缀


【代码】

class Solution {
public:
    string commonPrefix(vector<string>&strs, int from, int to){
        if(from==to) return strs[from];
        else{
            int mid=(from+to)/2;
            string prefix1=commonPrefix(strs, from, mid);
            string prefix2=commonPrefix(strs, mid+1, to);
            int p=0;
            while(p<prefix1.length() && p<prefix2.length() && prefix1[p]==prefix2[p])p++;
            if(p==prefix1.length())return prefix1;
            if(p==prefix2.length())return prefix2;
            return prefix1.substr(0,p);
        }
    }
    
    string longestCommonPrefix(vector<string> &strs) {
            int size=strs.size();
            if(size==0)return "";
            return commonPrefix(strs, 0, size-1);
    }
};