Easy readable c++ 6ms solution


  • 0
    M
        string longestCommonPrefix(vector<string>& strs) {
            string outstr="";
            int count = 0;
            //get maz size of the string.
            int maxS = -1;
            for(int i =0 ;i < strs.size();i++){
                if (maxS > strs[i].length())
                    maxS = strs[i].length();
            }
            while (count <= maxS){ 
               int dict[256]={0};
                
            for(int i =0 ;i < strs.size();i++ ){
                /// loop for all strings
                dict[strs[i][count]]++;
            }
                int max = -1;
                char ch;
                for(int i =0;i<256;i++){
                    if(dict[i]  > max){
                        max = dict[i];
                        ch = (char)i;
                    }
                }
                if(max < strs.size())
                    return outstr;
                else
                    outstr += ch;
                
                count++;
            }
            return outstr;
        }

Log in to reply
 

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