LeetCode Day12 longest-common-prefix

法一:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.empty()) return "";
        string res;
        for(int i=0;i<strs[0].size();i++){
            char temp=strs[0][i];
            for(int j=1;j<strs.size();j++){
                if(strs[j][i]!=temp) return res;
            }
            res+=temp;
        }
        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++){
            for(int j=0;j<strs.size()-1;j++){
                if(strs[j][i]!=strs[j+1][i]) return strs[j].substr(0,i);
            }
        }
        return strs[0];
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41394379/article/details/82996417