leetcode14 C++ 8ms 最长公共前缀

class Solution {
public:
    string prefix2(string& str1, string& str2){
        if(str1.empty() || str2.empty()){
            return "";
        }
        string res;
        auto sp1 = str1.begin();
        auto sp2 = str2.begin();
        while(sp1!=str1.end() && sp2!=str2.end()){
            if(*sp1 == *sp2){
                res.push_back(*sp1);
                sp1++;
                sp2++;
            }
            else{
                return res;
            }
        }
        return res;
    }
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.empty()){
        return "";
        }
        if(strs.size()==1){
        return strs[0];
        }

        string res = strs[0];
        for(int i=1; i < strs.size(); i++){
            res = prefix2(res, strs[i]);
        }

        return res;
    }
};
posted @ 2018-07-27 11:22  一条图图犬  阅读(619)  评论(0编辑  收藏  举报