首页 > 其他 > 详细

14. 最长公共前缀

时间:2020-03-17 00:01:30      阅读:101      评论:0      收藏:0      [点我收藏+]

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

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

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"
示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:

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

解:

当字符串数组长度为 0 时则公共前缀为空,直接返回
令最长公共前缀 ans 的值为第一个字符串,进行初始化
遍历后面的字符串,依次将其与 ans 进行比较,两两找出公共前缀,最终结果即为最长公共前缀
如果查找过程中出现了 ans 为空的情况,则公共前缀不存在直接返回
时间复杂度:O(s)O(s),s 为所有字符串的长度之和

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string str_front;

        for(int i=0;i<strs.size();i++)
        {
            if(i==0)
            {
                str_front=strs[i];
                continue;            
            }
            int num=min(str_front.size(),strs[i].size());
            string front_tmp;
            for(int index=0;index<num;index++)
            {
                //前面不相等,后面就不用比了
                if(str_front[index]==strs[i][index])
                {
                    front_tmp+=str_front[index];
                }
                else
                {
                    break;
                }
            }
            if(front_tmp.size()==0)
            {
                return front_tmp;
            }
            else
            {
                str_front=front_tmp;
            }
        }
        return str_front;
    }
};

 

14. 最长公共前缀

原文:https://www.cnblogs.com/wangshaowei/p/12507359.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!