[leetcode] 14. 最长公共前缀

14. 最长公共前缀

超级简单。。。

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        if (strs.size() == 0) {
            return "";
        }

        string common = strs[0];

        for (int i = 1; i < strs.size(); i++) {
            common = findCommon(strs[i], common);
        }

        return common;
    }

    string findCommon(string a, string b) {
        int len = min(a.size(), b.size());
        int k = 0;
        for (k = 0; k < len; k++) {
            if (a[k] != b[k]) {
                break;
            }
        }
        return a.substr(0, k);
    }
};
posted @ 2018-06-26 23:21  ACBingo  阅读(165)  评论(0编辑  收藏  举报