天天看点

LeetCode[String]: Longest Common Prefix

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

这个题目非常简单,只要弄清楚题意就可以非常快地解决,我的C++代码实现如下:

string longestCommonPrefix(vector<string> &strs) {
        if (strs.empty()) return "";

        string commonPrefix = strs[];
        for (int i = ; i < strs.size(); ++i) {
            int j = ;
            for ( ; j < commonPrefix.size() && j < strs[i].size(); ++j) {
                if (commonPrefix[j] != strs[i][j]) break;
            }
            commonPrefix = commonPrefix.substr(, j);
        }

        return commonPrefix;
    }
           

时间性能如下:

LeetCode[String]: Longest Common Prefix