Sharing 4ms C++ solution


  • 2
    T
    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            string result;
            int n = strs.size(), i, j;
            if(n==0)
                return result;
            int minLen = INT_MAX;
            for(i=0; i<n; i++)
                if(strs[i].length() < minLen)
                    minLen = strs[i].length();
                
            for(j=0; j<minLen; j++)
            {
                char c = strs[0][j];
                for(i=1; i<n; i++)
                    if(strs[i][j]!=c)
                        return result;
                result = result + c; 
            }
            
            return result;
        }   
    };

Log in to reply
 

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