8. 最长公共前缀子串

1. 题目描述

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

如果不存在公共前缀,返回空字符串 ""
8. 最长公共前缀子串
https://leetcode-cn.com/problems/longest-common-prefix/

2. 解法

思路:要求所有字符串的公共前缀,那么这个公共前缀一定小于等于任何一个字符串。不妨就以第一个字符串为匹配串,依次匹配后面所有的字符串。

talk is cheap,show me the code!

代码如下:

    string longestCommonPrefix(vector<string>& strs) {
        int size = strs.size();
        if(size <= 0)  return "";
        if(size == 1)  return strs[0];
        if(strs[0].size() <= 0)  return "";

        for(int index = 0; ; index++){
            char ch = strs[0][index];
            for(int i = 1; i < size; i++){
                if(strs[i].empty())  return "";    // 不足
                if(ch != strs[i][index])
                    return strs[i].substr(0, index);   // 中间断开
                if(strs[i].size() == index)         // 满了
                    return strs[i];
            }
        }
    }
上一篇:一和零(dp)


下一篇:Python 高级特性(1)