0
点赞
收藏
分享

微信扫一扫

Longest Common Prefix 字符的最长公共前缀


Longest Common Prefix


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

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        //遍历
        if(strs.size()==0)
            return "";
        else if(strs.size()==1)
            return strs[0];
        else{
            string res="";
            int i,k=0;
            char c=strs[0][0];
            while(1)
            {
                 for(i=0;i<strs.size();i++)
                 {
                        if(k<strs[i].size()&&strs[i][k]==c)
                        {
                            if(i==strs.size()-1)
                            {
                                res+=c;
                                k++;
                                c=strs[0][k];
                            }
                        }
                        else
                        {
                            return res;
                        }
                 }
             }
         }
    
    }
};

举报

相关推荐

0 条评论