Longest Common Prefix

来源:互联网 发布:js中json删除指定元素 编辑:程序博客网 时间:2024/05/16 18:54
class Solution {public:    string longestCommonPrefix(vector<string> &strs) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int LCP=0,i,j;        string s="";        if(strs.size()==0)return s;        if(strs.size()==1)return strs[0];        s=strs[0];        while(true){            for(i=1;i<strs.size();++i){                string s1=s.substr(0,LCP);                string s2=strs[i].substr(0,LCP);                if(LCP>s.size()||LCP>strs[i].size()||s1!=s2)                    break;            }            if(i==strs.size())                LCP++;            else break;        }        //if strs= ["a","b"],LCP = 1, because we start LCP=0, which means there will always have one common prefix ""         return s.substr(0,LCP-1);    }};