Longest Common Prefix

来源:互联网 发布:电脑软件应用商店 编辑:程序博客网 时间:2024/05/17 00:12

题目

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

实现一

class Solution {public:    string longestCommonPrefix(vector<string> &strs) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        string res = "";        if(strs.size()<=0)            return res;        int minlen = strs[0].size();        for(int i=1;i<strs.size();i++)            if(strs[i].size()<minlen)                minlen = strs[i].size();             int ind=0;        while(ind<minlen)        {            for(int i=1;i<strs.size();i++)            {                if(strs[i][ind]!=strs[i-1][ind])                    return res;            }            res +=strs[0][ind];            ind++;        }        return res;            }};


实现二


class Solution {public:    string longestCommonPrefix(vector<string> &strs) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        string res = "";        if(strs.size()<=0)            return res;        int len = strs.size();        int ind=0;        for(int i=0;i<strs[0].size();i++)        {            for(int j=1;j<strs.size();j++)            {                if(i>=strs[j].size() || strs[j][i]!=strs[0][i])                    return strs[0].substr(0,i);            }        }        return strs[0];            }};






原创粉丝点击