A rude force solution, need some improvement advices


  • 0
    S

    // any advice will be welcome

    string longestCommonPrefix(vector<string> &strs) {
            string str;
            if (strs.size() <= 0) return str;
    
            // get min len
            int min = strs[0].size();
            for (int i = 1; i < strs.size(); ++i) {
                if(strs[i].size() < min)
                    min = strs[i].size();
            }
            
            // compare each char
            for (int i = 0; i < min; ++i) {
                char c = strs[0].at(i);
                for (int j = 1; j < strs.size(); ++j) {
                    if (c != strs[j].at(i))
                        return str;
                }
                str.append(1, c);
            }
            
            return str;
        }

Log in to reply
 

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