6ms 7 lines c++


  • 0
    T
    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            int num= strs.size(), len=INT_MAX;
            for(int i=0;i<num;i++) if (strs[i].size()<len) len=strs[i].size();// find out the minimum length among the strings
            if (num==0 || len==0) return "";
            for(int i=0;i<len;i++)
                for(int j=1;j<num;j++)
                    if (strs[j][i]!=strs[j-1][i]) return strs[j].substr(0,i);// find the longest 
            return strs[0].substr(0,len);// the answer is one of the strings
        }
    };
    

Log in to reply
 

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