面试经典题---14.最长公共前缀

14.最长公共前缀

我的解法:

主要思路是定义一个函数longestCommonPrefix(const string s1,const string s2)用于获取字符串s1和s2的最长公共前缀字符串,之后依次计算strs中的相邻字符串的最长公共前缀。

  • cmp初值为strs中的第一个字符串strs[0];
  • 依次计算cmp与strs中后一个字符的最长公共前缀,并以该前缀来更新cmp;
  • 一旦发现cmp长度为0,则直接break
class Solution {
public:
    string longestCommonPrefix(const string s1,const string s2){
        int len = min(s1.size(),s2.size());
        int i = 0;
        while(i < len && s1[i] == s2[i]){
            ++i;
        }
        return s1.substr(0,i);
    }
    string longestCommonPrefix(vector& strs) {
        string cmp = strs[0];
        for(int i = 1; i < strs.size(); ++i){
            cmp = longestCommonPrefix(cmp,strs[i]);
            if(cmp.size() == 0){
                break;
            }
        }
        return cmp;
    }
};

可以一开始加一个判断:若strs的大小为0,则直接返回空字符串""

你可能感兴趣的:(算法,leetcode,c++)