C++ hash map 32%


  • 0
    class Solution {
    public:
        void work(vector<string>& words, vector<vector<string>>& ans, int idx, string prefix, vector<string>& sq, unordered_map<string,set<string>>& map) {
            int len = words[0].size();
            if(idx==len) {
                ans.push_back(sq);
                return;
            }
            for(string s : map[prefix]) {
                sq.push_back(s);
                string p="";
                for(string ss : sq) {
                    p += ss[idx+1];
                }
                work(words,ans,idx+1,p,sq,map);
                sq.pop_back();
            }
            
        }
        vector<vector<string>> wordSquares(vector<string>& words) {
            vector<string> sq;
            vector<vector<string>> ans;
            unordered_map<string,set<string>> map;
            int n = words[0].size();
            for(string word : words) {
                for(int i=0;i<n;i++) {
                    map[word.substr(0,i)].insert(word);
                }
            }
            work(words,ans,0,"",sq,map);
            return ans;
        }
    };
    

Log in to reply
 

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