14. Longest Common Prefix

Problem:

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.

思路

先求出最短的字符长度,然后从第一个字符串的第一个字符开始,判断是不是所有字符串的对应位字符相等,然后依次比较剩下的字符。这种解法思路很简单,相应的,性能也很低。

Solution (C++):

string longestCommonPrefix(vector<string>& strs) {
    if (strs.empty()) return "";
    
    int min_len = INT_MAX;
    
    for (auto str: strs)  {
        if (str.size() < min_len)
            min_len = str.size();
    }
    
    string pre = "";
    bool flag = true;
    
    for (int i = 0; i < min_len; ++i) {
        char a = strs[0][i];
        for (auto str: strs) {
                if (str[i] != a) { flag = false; break; }
        }
        if (flag) 
            pre += a;
    }
    
    return pre;
}

性能

Runtime: ms  Memory Usage: MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12570849.html