leetcode Longest Common Prefix

来源:互联网 发布:c语言程序小游戏 编辑:程序博客网 时间:2024/06/09 22:18

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

思想很简单,就是边界问题的处理,采用了re=strs[0],避免边界处理

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        int len=strs.size();
        if(len==0) return "";
        string re=strs[0];
        for(int i=0;i<len;i++){
            re=sub(strs[i],re);
        }
        return re;
    }
public:
    string sub(string str1,string str2){
        string re="";
        int i=0,len1=str1.length(),len2=str2.length();
        while(i<len1&&i<len2&&str1[i]==str2[i]){
            re+=str1[i];
            i++;
        }
        return re;
    }
};

0 0
原创粉丝点击