Skip to content

Commit 8282945

Browse files
committed
Changes for Leetcode problems
1 parent 27d4e68 commit 8282945

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Google Questions/Word Squares.js

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// https://leetcode.com/explore/interview/card/google/62/recursion-4/370/
2+
3+
/**
4+
* @param {string[]} words
5+
* @return {string[][]}
6+
*/
7+
var wordSquares = function(words) {
8+
let wordMap = {};
9+
for(let word of words){
10+
for(let i in word){
11+
let substr = word.substr(0, i);
12+
if(!wordMap.hasOwnProperty(substr)){
13+
wordMap[substr] = [];
14+
}
15+
wordMap[substr].push(word);
16+
}
17+
}
18+
19+
let squares = [];
20+
for(let word of words){
21+
squares = [...squares, ...findSquares(wordMap, [word], word.length)];
22+
}
23+
return squares;
24+
};
25+
26+
var findSquares = function(wordsMap, curSquare, wordLength) {
27+
let i = curSquare.length;
28+
if(i >= wordLength){
29+
return [curSquare];
30+
}
31+
let nextWordStart = curSquare.map(w => w[i]).join('');
32+
33+
if(wordsMap.hasOwnProperty(nextWordStart)){
34+
let squares = [];
35+
for(let word of wordsMap[nextWordStart]){
36+
//if(curSquare.indexOf(word) == -1){
37+
squares = [...squares, ...findSquares(wordsMap, [...curSquare, word], wordLength)];
38+
//}
39+
}
40+
return squares;
41+
}
42+
return [];
43+
}

0 commit comments

Comments
 (0)