LeetCode——最长公共前缀

题目地址:https://leetcode-cn.com/problems/longest-common-prefix

解题思路:暴力

class Solution {
private:
    string    getAns(string a,string b) {
        int len = min(a.size(), b.size());
        int i;
        for (i = 0; i < len; i++)
            if (a[i] != b[i])
                break;
        return a.substr(0, i);
    };
public:
    string longestCommonPrefix(vector<string>& strs) {
        string ans;
        if (!strs.size()) {
            return "";
        }
        int size = strs.size();
        ans = strs[0];
        for (int i = 1; i < size; i++){
            ans = getAns(ans, strs[i]);
            if(!ans.size())
                break;
        }
        return ans;
    }
};

 

posted @ 2020-07-28 16:18  CCxiao5  阅读(84)  评论(0编辑  收藏  举报