15算法课程 14. Longest Common Prefix

来源:互联网 发布:淘宝网抢红包 编辑:程序博客网 时间:2024/06/04 20:46

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

solution:

先将数组排序,之后将第一个和最后一个比对

code:

class Solution {public:    string longestCommonPrefix(vector<string>& strs) {        string ret("");        int N = strs.size();        if(N == 0) return ret;        unsigned int i = 0;        while(1)        {            char a;            if(strs[0].size() > i)            {                a = strs[0][i];            }            else            {                return ret;            }            for(int j = 1; j < N; j++)            {                if(strs[j].size() <= i || strs[j][i] != a)                {                    return ret;                }            }            ret.push_back(a);            i++;        };        return ret;// 这一行是永远执行不到的    }};


原创粉丝点击