您的位置:首页 > 其它

leetcode-14 Longest Common Prefix

2015-04-07 18:51 302 查看
算法1:逐个字符比较,时间复杂度为O(N*L),N是字符串个数,L是最长前缀的长度

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        string res;
        int len = strs.size();
        if(len == 0) return res; //这句一定得有,如果不加的话,第一个for循环运行到strs[0].size(),就会出现runtime error,因为根本就没有strs[0]
        int i,j;
        for(i = 0; i < strs[0].size(); i++){
            for(j = 1; j < len; j++){
                if(strs[j].size() == i || strs[j][i] != strs[0][i])
                    return res;
            }
            res.push_back(strs[0][i]);
        }
        return res;
    }
};


参考:http://www.cnblogs.com/TenosDoIt/p/3856331.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: