[Leetcode]Longest Common Prefix

来源:互联网 发布:大数据时代联系的特点 编辑:程序博客网 时间:2024/06/16 14:49

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

class Solution {public:    /*algorithm      loop from len = 0 to maxlen of strings      each loop check whehter the substr(0,len) is all prefix for all strings      time O(n*n) space O(1)    */    bool isMatch(string &s,int len,string &match){         int i = 0;         while(i < len && s[i] == match[i])++i;         return i == len;    }    string longestCommonPrefix(vector<string>& strs) {            if(strs.size() < 1)return "";            int len = 0;            int maxLen = 1;            bool exit = false;            for(;len <= maxLen;len++){                for(int i = 0;i < strs.size();i++){                    maxLen = max(maxLen,(int)strs[i].size());                    if(!isMatch(strs[i],len,strs[0])){                        exit = true;                        break;                    }                }                if(exit)break;            }            return len > 0 ?strs[0].substr(0,len - 1):"";    }};


0 0
原创粉丝点击