[leetcode] 14 longest common prefix

Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.

最长公共前缀

看到前缀 我就想到了tries 树, 但是一看这题是easy........
我们假设 有 N个字符串 , 平均长度为 M
我们暴力比较 第 i (0..m) 位, 复杂度为 N*M
其实用 tries树 时间复杂度反而高,而且还要开空间。。。
所以这题就暴力比较啦。

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        
        if(strs.empty())
            return "";
        
        // 特殊处理 strs 只有一个字符串 的情况 
        if(strs.size()==1){
            return strs[0];
        }
        
        int ptr = 0;
        // 循环比较 每个字符串的 第 i 位 
        
        while(true){
            
            // 循环 比较! 如果出现 1. 前后不一致  或者  2. 某一字符串越界 
            // 这个循环 不能处理 strs.size() <=1 的情况 所以上面要特殊处理
            for(int i =1; i <strs.size();++i){
                if( ptr == strs[i].size() || strs[i][ptr] != strs[i-1][ptr]){
                    //结束循环 打印结果
                    return strs[0].substr(0,ptr);
                }
            }
            ptr++;
        }
 
    }
};
image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,957评论 19 139
  • Write a function to find the longest common prefix string...
    xxx亦凡桑阅读 188评论 0 0
  • 问题描述: Write a function to find the longest common prefix ...
    去留无意hmy阅读 486评论 0 1
  • 今天是春节,虽然昨晚熬夜守岁,可依然可以很早起来,这就是过年的力量。 走出家门,给邻里乡亲们拜拜年。...
    陕县2896杜媛媛阅读 171评论 2 1
  • 趁着回乡,携着小女,打算重温下儿时野趣… 曾经的野草滩,小水塘成了玉米田,刚刚掰完玉米的秸秆七零八落散乱在田里;曾...
    shstray阅读 179评论 0 0