C++ solution (beats 94.9% submissions)


  • 0
    M
    class Solution {
    public:
        bool validWordSquare(vector<string>& words) {
            int num_of_str = words.size();
            int max_str_size = 0;
    
            for(auto it = words.begin(); it != words.end(); ++it){
                if((*it).length() > max_str_size){
                    max_str_size = (*it).length();
                }
            }
            
            if(num_of_str != max_str_size){
                return false;
            }else{
                char** vert_arr = new char*[num_of_str];
                for(int i = 0; i < num_of_str; ++i){
                    vert_arr[i] = new char[max_str_size]();
                }
                for(int i = 0; i < num_of_str; ++i){
                    int str_len = words[i].length();
                    for(int j = 0; j < str_len; ++j){
                        vert_arr[i][j] = words[i][j];
                    }
                }  
    
                for(int i = 0; i < num_of_str; ++i){
                    for(int j = i; j < max_str_size; ++j){
                        if(vert_arr[i][j] != vert_arr[j][i]){
                            return false;
                        }
                    }
                }
                for(int i = 0; i < num_of_str; ++i){
                    delete [] vert_arr[i];
                }
                delete [] vert_arr;
                return true;
            }
        }
    };
    

Log in to reply
 

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