LeetCode 14.最长公共前缀

目录

 

0. 题目描述

1. 解题分析

2. 优质范例


0. 题目描述

1. 解题分析

(1)查找一个数组中的公共前缀,随便选取其中一个字符串,然后顺序遍历它的字符,并遍历判断数组中其他字符串是否包含这个字符即可。

static auto _=[]()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    return 0;
}();


class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int strSize = strs.size();

        if (strSize == 0) {
            return "";
        }

        if (strSize == 1) {
            return strs.front();
        }

        int lcp = 0;
        bool flag = true;

        while (flag) {
            for (int i = 1; i < strSize; ++i) {
                if (strs[i][lcp] != strs[0][lcp]) {
                    flag = false;
                    break;
                }
            }
            lcp++;
        }

        if (lcp == 1) return "";
        return strs[0].substr(0, lcp - 1);
    }
};

复杂度分析

  • 时间复杂度:O(n)。
  • 空间复杂度:O(n)。

2. 优质范例

 

猜你喜欢

转载自blog.csdn.net/weixin_40801204/article/details/82846393