Longest Common Prefix

Description:

Write a function to find the longest common prefix string amongst an array of strings.(最长公共字串)

Code:

string merge(string&str1, string&str2)
    {
        string result="";
        int n = (str1.size()<=str2.size())?str1.size():str2.size();
        for (int i = 0; i < n; ++i)
        {
            if (str1[i]==str2[i])
                result=result+str1[i];
            else
                return result;
        }
        return result;
    }
    string longestCommonPrefix(vector<string>& strs, int start, int end)
    {
        if (start < end)
        {
            int middle = (start+end)/2;
            string str1 = longestCommonPrefix(strs, start, middle);
            if (str1=="")
                return str1;
            string str2 = longestCommonPrefix(strs, middle+1, end);
            if (str2=="")
                return str2;
            return merge(str1, str2);
        }
        else
            return strs[start];
    }
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.size()==0)
            return "";
        return longestCommonPrefix(strs,0,strs.size()-1);
    }

 

posted @ 2015-09-01 10:36  Rosanne  阅读(182)  评论(0编辑  收藏  举报