leetcode 最长公共前缀 简单

 

 

 很容易想到的暴力:枚举前缀,对每个前缀在每个字符串中挨个字符,依次对比。时间复杂度 n^3

代码:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        sort(strs.begin(), strs.end(), [](const string &a, const string &b) {
            return a.size() < b.size();
        });
        string ans = "";
        for(int i = 0; i < strs[0].size(); ++ i) {
            ans.push_back(strs[0][i]);
            bool flag = true;
            for(int j = 1; j < strs.size(); ++ j) {
                if(!check(strs[j], ans)) flag = false;
            }
            if(!flag) return ans.empty() ? "" : (ans.pop_back(), ans);
        }
        return ans;
    }
    
    bool check(const string& s, const string& pre) {
        if(s.size() < pre.size()) return false;
        for(int i = 0; i < pre.size(); ++ i) {
            if(s[i] != pre[i]) return false;
        }
        return true;
    }
};

然后稍微一想,发现 check 根本没必要用for,所以复杂度变为 n^2

这样修改:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        sort(strs.begin(), strs.end(), [](const string &a, const string &b) {
            return a.size() < b.size();
        });
        string ans = "";
        for(int i = 0; i < strs[0].size(); ++ i) {
            ans.push_back(strs[0][i]);
            bool flag = true;
            for(int j = 1; j < strs.size(); ++ j) {
                if(!check(strs[j], ans)) flag = false;
            }
            if(!flag) return ans.empty() ? "" : (ans.pop_back(), ans);
        }
        return ans;
    }

    bool check(const string& s, const string& pre) {
        if(s.size() < pre.size()) return false;
        return s[pre.size() - 1] == pre.back();
    }
};

 

posted @ 2021-07-22 00:10  rookie_Acmer  阅读(34)  评论(0)    收藏  举报