11 lines concise and easy understand c++ solution


  • 1
    A
    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if(strs.size() == 0) return "";
            string res = strs[0];
            for(auto str : strs){
                int len = 0;
                for(int i = 0; i < res.size() && i < str.size(); i++){
                    if(res[i] == str[i]) len++;
                    else break;
                }
                res = res.substr(0, len);
            }
            return res;
        }
    };

Log in to reply
 

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