ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

LeetCode-14-最长公共前缀

2021-01-14 00:01:29  阅读:11  来源: 互联网

标签:tmp 前缀 strs res str1 int 14 LeetCode string


题目

14-最长公共前缀
https://leetcode-cn.com/problems/longest-common-prefix/在这里插入图片描述

题解

以为很暴力的方法其实最快,其他的思路也值得参考,要自己分析复杂度todo
https://leetcode-cn.com/problems/longest-common-prefix/solution/zui-chang-gong-gong-qian-zhui-by-leetcode-solution/

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int strs_size = strs.size();
        if (strs.empty()) {return "";}
        string res = strs[0];
        int index = 1;
        while (index < strs_size) {
            res = strCmp(res, strs[index]);
            if (res == "") {
                break;
            }
            index++;
        }
        return res;
    }
    string strCmp(string str1, string str2) {
        int min_length = min(str1.length(), str2.length());
        int i = 0;
        string tmp_res = "";
        while (i < min_length) {
            if (str1[i] != str2[i]) {
                return tmp_res;
            }
            // tmp_res.append(str1[i]);
            tmp_res.push_back(str1[i]);
            i++;
        }
        return tmp_res;
    }
};

标签:tmp,前缀,strs,res,str1,int,14,LeetCode,string
来源: https://blog.csdn.net/yifen4234/article/details/112597419

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有