LeetCode-14-最长公共前缀

题目

14-最长公共前缀
https://leetcode-cn.com/problems/longest-common-prefix/LeetCode-14-最长公共前缀

题解

以为很暴力的方法其实最快,其他的思路也值得参考,要自己分析复杂度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;
    }
};
上一篇:14. 最长公共前缀、Leetcode的Go实现


下一篇:Task03——采用C++