C++ 6ms


  • 0
    R

    class Solution {
    public:
    string longestCommonPrefix(vector<string>& strs) {
    int n = strs.size();
    if(strs.empty())
    return "";
    int min_len=strs[0].size(),idx=0;
    if(min_len==0)
    return "";
    for(int i=1;i<n;i++){
    if(strs[i].size()<min_len){
    min_len = strs[i].size();
    idx = i;
    }
    }
    string minstring = strs[idx];
    for(int i=0;i<n;i++){
    string s1 = strs[i];
    int l = s1.size();
    for(int j=0;j<min(l,min_len);j++){
    if(s1[j]!=minstring[j]){
    min_len = j;
    break;
    }
    }
    if(min_len==0)
    break;
    }
    return minstring.substr(0,min_len);
    }
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.