LeetCode 14. 最长公共前缀 Longest Common Prefix

时间复杂度O(s),s为所有字符长度和。

空间复杂度O(1)。

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string res = strs.size() ? strs[0] : "";
        for (auto s : strs)
        {
            while (s.substr(0, res.size()) != res)
            {
                res = res.substr(0, res.size() - 1);
                if (res == "") return res;
            }
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/ZSY-blog/p/12951687.html