Longest Common Prefix

来源:互联网 发布:出国留学 知乎 编辑:程序博客网 时间:2024/05/20 17:41

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

实现:

class Solution {public:    string longestCommonPrefix(vector<string>& strs) {        string res = "";        int cnt = 0;        if(strs.size() == 0 )            return res;        if(strs.size() == 1)            return strs[0];        while(true){            if(cnt >= strs[0].size()){                return res;            }            char ch = strs[0][cnt] ;            bool flag = false;            for(int i = 1 ; i < strs.size(); ++i){                if(cnt>=strs[i].size() || strs[i][cnt]!=ch){                    flag = true;                    break;                }            }            if(flag||strs.size()<=1)               break;             res+=ch;            ++cnt;        }        return res;    }};

自己的实现过于复杂,有简单的实现方式:

class Solution {public:    string longestCommonPrefix(vector<string>& strs) {        string res = "";        for(int i = 0;strs.size() > 0;res+=strs[0][i],++i){            for(int j = 0 ; j < strs.size() ; ++j){                if(i >= strs[j].size() || (j > 0 && strs[j-1][i] != strs[j][i]))                    return res;            }        }        return res;    }};
0 0
原创粉丝点击