LeetCode 14 - Longest Common Prefix

一、问题描述

Description:

Write a function to find the longest common prefix string amongst an array of strings.

给定一组字符串,写一个函数找出它们的最长公共前缀。


二、解题报告

首先,我尝试用 Trie 树去求公共前缀,但是超过了内存限制:Memory Limit Exceeded

后来仔细一想,其实不需要那么麻烦。可以直接用 最短的字符串 作为基准,把其他的字符串和最短字符串比较,标记公共前缀的截止位置即可。

bool cmp(string &s1, string &s2) {
    return s1.size() < s2.size();
}

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

        // 按字符串长度从小到大排序
        sort(strs.begin(), strs.end(), cmp); 

        // 其他字符串都和第一个字符串比较
        for(int i=1; i<strs.size(); ++i) {   
            for(int j=0; j<strs[i].size(); ++j) {
                if(strs[i][j] != strs[0][j]) {
                    strs[0][j] = '\0';   // 标记公共前缀截止位置
                    break;
                }
            }
        }

        int pos = strs[0].find('\0');
        if(pos < 0)
            return strs[0];
        else
            return strs[0].substr(0,pos);
    }
};





LeetCode答案源代码:https://github.com/SongLee24/LeetCode


转载于:https://www.cnblogs.com/songlee/p/5738053.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值