LeetCode 14. Longest Common Prefix

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 14. Longest Common Prefix相关的知识,希望对你有一定的参考价值。

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

让我们在一个字符串中找出所有字符串的共同前缀

 

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string result = "";
        if (!strs.size())return result;
        result = strs[0];
        for (auto &e : strs)
        {
            if (e.size() < result.size())
                result = e;
        }
        for (auto &e : strs)
        {
            int i = 0;
            for (;i < result.size();++i)
            {
                if (e[i] != result[i])break;
            }
            result=result.substr(0, i);
        }
        return result;
    }
};

 

以上是关于LeetCode 14. Longest Common Prefix的主要内容,如果未能解决你的问题,请参考以下文章

leetcode14. longest common prefix

Leetcode 14. Longest Common Prefix

Leetcode 14 Longest Common Prefix

Leetcode14. Longest Common Prefix

LeetCode 14: Longest Common Prefix

leetcode 14. Longest Common Prefix