*14_longest_common_prefix 最长公共前缀

2020-02-29  本文已影响0人  lazy_ccccat

题目描述

14. 最长公共前缀

思路

1.这个思路得好好想想,逻辑好好想想,很容易写错。debug了好几次外加瞄一眼答案才写对。
值得再写一遍
2.我本来想着是找下标,然后substr。其实可以用string的push_back(char)

代码

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.empty()) return "";
        string res;
        for (int i = 0; i < strs[0].size(); i++) {
            char c = strs[0][i];
            bool flag = false;
            for (string str: strs) {
                if (i > str.size() - 1 || c != str[i]) flag = true;
            }
            if (!flag) {
                res.push_back(c);
            } else {
                break;
            }
        }
        return res;
        
    }
};

其实也不用写这么复杂,有更简洁的写法:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.empty()) return "";
        string res;
        for (int i = 0; i < strs[0].size(); i++) {
            char c = strs[0][i];
            for (string str: strs) {
                if (i > str.size() - 1 || c != str[i]) return res; 
            }
            res.push_back(c);
        }
        return res;
        
    }
};
上一篇 下一篇

猜你喜欢

热点阅读