My c++ solution, beat 50%.


  • 0
    M
    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            
            if(strs.size() == 0) return "";
            
            int minlength = strs[0].size();
            for(int i = 1;i < strs.size(); i++){
                if(strs[i].size() < minlength) minlength = strs[i].size();
            }
            
            string res = "";
            for(int i = 0;i < minlength; i++){
                char ch = strs[0][i];
                for(int j = 1; j < strs.size(); j++){
                    if(strs[j][i] != ch) return res;
                }
                res += ch;
            }
            
            return res;
        }
    };

Log in to reply
 

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