Leetcode-Longest Common Prefix

来源:互联网 发布:windows程序开发工具 编辑:程序博客网 时间:2024/05/19 17:03

题目:

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

要求找出所有string的最长前缀。可以选择横向比较,两两比较找出最长的前缀,不断比较,不断更新,但考虑了极端情况,假设相同的最长前缀呈阶梯分布,则做了许多无用功。纵向逐个字符比较,显然简单许多。代码如下:

class Solution {public:    string longestCommonPrefix(vector<string>& strs) {        string res;        int n = strs.size();        if(n == 0) return res;        //if(n == 1) {        //res = strs[0];        //return res;        //}        for(int x = 0; x < strs[0].size(); x++) {        for(int y = 1; y < n; y++) {        if(strs[y].size() < (x+1) || strs[y][x] != strs[0][x]) {        return res;        }        }        res.push_back(strs[0][x]);        }        return res;    }};

原创粉丝点击