浅谈 各字符串最长公共前缀 问题

各字符串最长公共前缀

题目: 编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

说明:
所有输入只包含小写字母 a-z 。

思路:

  1. 先考虑两个字符串最长公共长度
  2. 然后保存相同最长公共长度字符串再与后面字符串比较
class Solution {
    
    
public:
    string longestCommonPrefix(vector<string>& strs) {
    
    
        if(!strs.size()) return "";
        string str = strs[0];
        int count = strs.size();
        for(int i = 1; i < count; ++i){
    
    
            str = longestCommonPrefix(str, strs[i]);
            if(str == ""){
    
    
                break;
            }
        }
        return str;
    }

    string longestCommonPrefix(const string& str1, const string& str2){
    
    
        int len = min(str1.size(), str2.size());
        int index = 0;
        for(int i = 0; i < len; ++i){
    
    
            while(index < len && str1[index] == str2[index]){
    
    
                index++;
            }
        }
        return str1.substr(0, index);
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_48033173/article/details/112055671
今日推荐