Leetcode题解-14. Longest Common Prefix

来源:互联网 发布:js length 编辑:程序博客网 时间:2024/06/01 17:09

Leetcode题解-14. Longest Common Prefix

给出一个字符串数组,求出所有字符串最长的公共前缀

思路

 想法1:对每个字符串相同位置的字符进行比较,直到出现不同字符或者超过其中一个字符串长度结束比较
 想法2:每次将前缀和一个字符串的比较,取前缀和该字符串的最长公共前缀,直到比较完所有字符串

代码

想法1的代码

string longestCommonPrefix(vector<string>& strs) {        int l = strs.size();        string res = "";        if(l == 0) return "";        if(l == 1) return strs[0];        int count = 0;        while(1){            char c = strs[0][count];            for(int i = 0; i < l; i++){                if(strs[i][count] != c || strs[i][count] == '/0'){                    return res;                }            }            res += c;            cout << 1 << endl;            count++;            if(count >= strs[0].size()) return res;        }    }

想法2的代码

string longestCommonPrefix(vector<string>& strs) {        int l = strs.size();        string res = "";        if(l == 0) return "";        if(l == 1) return strs[0];        res = strs[0];        for(int i = 1; i < l; i++){            int len = (res.size() > strs[i].size()) ? strs[i].size() : res.size();            int j;            for(j = 0; j < len; j++){                if(res[j] != strs[i][j]) break;            }            res = res.substr(0,j);        }        return res;    }