LeetCode 14

一、问题描述

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] = '';   // 标记公共前缀截止位置
                    break;
                }
            }
        }

        int pos = strs[0].find('');
        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