easy to follow c++ solution


  • 0
    G
    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            
            if(strs.empty()){
                return "";
            }
            
            sort(strs.begin(),strs.end(),[](const string s1, const string s2)->bool{
               return s1.size() < s2.size(); 
            });
            
            string prefix = strs[0];
            
            for(int i = 1; i < strs.size(); ++i){
                for(int c = 0; c < prefix.size(); ++c){
                    if(strs[i][c] != prefix[c]){
                        prefix = prefix.substr(0,c);
                        break;
                    }
                }
            }
            return prefix;
        }
    };
    

Log in to reply
 

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