【easy!】LeetCode 14. Longest Common Prefix

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Allenlzcoder/article/details/80689250

LeetCode 14. Longest Common Prefix

Solution1:
用的暴力遍历,时间复杂度O(n2)

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int n = strs.size();
        if (n == 0) return "";
        else if (n == 1) return strs[0];
        string common_pre = strs[0];
        for (int i = 1; i < n; i++) {
            if (common_pre.size() == 0) return "";
            if (common_pre.size() > strs[i].size())
                common_pre.erase(strs[i].size());
            for (int j = 0; j < common_pre.size(); j++) {
                if (common_pre[j] != strs[i][j]) {
                    common_pre.erase(j);
                    break;
                }
            }
        }
        return common_pre;
    }
};
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页