Leetcode.14 最长公共前缀

首页 / 💻 代码 / 正文

题目简介

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。


提示:

1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 仅由小写英文字母组成


代码模板

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {

    }
};

最终代码

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int n = strs.size();
        string sum="";
        if (n == 0)
            sum = "";
        else if (n == 1)
            sum = strs[0];
        else if (n >= 2)
        {
            for (int j = 1, jump = false;; j++)
            {
                for (int i = 1; i < n; i++)
                {
                    if (strs[i-1].empty()||strs[i].empty()||j>strs[i].size()||j>strs[i-1].size()||strs[i - 1][j - 1] != strs[i][j - 1])
                    {
                        jump = true;
                        break;
                    }
                }
                if (jump == false)
                {
                    sum += strs[0][j - 1];
                }
                else
                {
                    break;
                }
            }
        }
        return sum;
    }
};

if的判断条件有点长,可以简化一下。
{4BBB5694-5804-4a5f-B1D5-88FC776D96A6}.png


打赏qwq
文章目录