7 lines, 4ms, C++


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

  • 0
    J

    Is this based on the assumption that all the strings in the vector "strs" share the same length?


Log in to reply
 

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