码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 14. 最长公共前缀

时间:2020-01-27 00:15:43      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:lin   comm   class   longest   int   prefix   return   time   时间复杂度   

题意

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

思路

直接判断就好了,时间复杂度\(O(len \times 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%,头一回。

LeetCode 14. 最长公共前缀

标签:lin   comm   class   longest   int   prefix   return   time   时间复杂度   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!