-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path30-002.js
85 lines (75 loc) · 1.76 KB
/
30-002.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* @param {string} s
* @param {string[]} words
* @return {number[]}
*/
var findSubstring = function(s, words) {
if (!words[0]) {
return [];
}
let length = s.length;
let wordLength = words[0].length;
let wordNumber = words.length;
if (length < wordNumber * wordLength) {
return [];
}
let res = [];
let wordsMap = {};
let i = 0;
let key;
words.forEach(word => {
if (wordsMap[word] === undefined) {
wordsMap[word] = 1;
} else {
wordsMap[word]++;
}
});
while (i + wordNumber * wordLength <= length) {
key = s.substring(i, i + wordLength);
if (wordsMap[key] !== undefined) {
if (isFound(wordNumber, i)) {
res.push(i);
}
}
i++;
}
return res;
function isFound(wordNumber, start) {
let newMap = cloneMap();
while (true) {
newMap[key]--;
if (newMap[key] < 0) {
return false;
}
wordNumber--;
if (wordNumber === 0) {
return true;
}
start += wordLength;
key = s.substring(start, start + wordLength);
if (wordsMap[key] === undefined) {
return false;
}
}
}
function cloneMap() {
let newMap = {};
Object.keys(wordsMap).forEach(key => {
newMap[key] = wordsMap[key];
});
return newMap;
}
};
let s = "barfoothefoobarman";
let words = ["foo", "bar"];
// s = "wordgoodgoodgoodbestword";
// words = ["word", "good", "best", "word"];
// s = "";
// words = [];
// s = "barfoofoobarthefoobarman";
// words = ["bar", "foo", "the"];
// s = "wordgoodgoodgoodbestword";
// words = ["word", "good", "best", "good"];
// s = "aaaaaaaa";
// words = ["aa", "aa", "aa"];
console.log(findSubstring(s, words));