C++ simple solution 9ms


  • 0
    R
        string longestCommonPrefix(vector<string>& strs) {
            int minSize = strs.size() == 0 ? 0 : INT_MAX;
            for(int i = 0; i < strs.size(); i++)
                minSize = min((int) strs[i].size(), minSize);
            
            string ret = "";
            for(int i = 0; i < minSize; i++) {
                char c = strs[0][i];
                for(int j = 0; j < strs.size(); j++) {
                    if(strs[j][i] != c) return strs[j].substr(0, i);
                }
                ret+=c;
            }
            
            return ret;
        }
    

Log in to reply
 

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