LeetCode 14. 最长公共前缀

题意

输出字符串数组中所有字符串的最长公共前缀。

思路

直接判断就好了,时间复杂度(O(len imes n))(n)为字符串的数量,(len)为所有字符串中最短的字符串的长度。

代码

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {

        if(strs.size() == 0)    return "";

        int tot = strs.size();
        int len = strs[0].size();
        for(int i = 1; i < tot; ++i)
            len = min(len, (int)strs[i].size());

        string res = "";
        bool flag = true;
        for(int i = 0; i < len; ++i)
        {
            for(int j = 1; j < tot; ++j)
                if(strs[j][i] != strs[0][i])
                    flag = false;
            if(flag)
                res += strs[0][i];
            else
                break;
        }
        return res;
    }
};

总结

战胜95%,头一回。

原文地址:https://www.cnblogs.com/songjy11611/p/12235215.html