Simple C++ solution


  • 0
    G
        string longestCommonPrefix(vector<string>& strs) {
            string r("");
            if (strs.empty()) return r;
            for (int i = 0; i < strs[0].size(); i++) {
                bool mis_match = false;
                for (int j = 1; j < strs.size(); j++) {
                    if (strs[j][i] != strs[0][i]) {
                        mis_match = true;
                        break;
                    }
                }
                if (mis_match) return r;
                else r.push_back(strs[0][i]);
            }
            return r;
        }
    

  • 0
    H

    using this you should guarantee strs[0] is the shortest in the vector. Otherwise strs[j][i] will be meaningless.


Log in to reply
 

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