Simple C++ solution


  • 0
    M
    string longestCommonPrefix(vector<string> &strs) {
            if (strs.empty())
                return "";
        
            string longestPrefix = strs[0];
        
            for (int i = 1; i < strs.size(); ++i)
            {
                int j = 0;
                while (j < strs[i].size() && j < longestPrefix.size() && strs[i][j] == longestPrefix[j])
                {
                    ++j;
                }
                longestPrefix = longestPrefix.substr(0, j);
            }
        
            return longestPrefix;
        }

Log in to reply
 

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