forked from jeantimex/javascript-problems-and-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubstring-with-concatenation-of-all-words.js
64 lines (56 loc) · 1.67 KB
/
substring-with-concatenation-of-all-words.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
/**
* Substring with Concatenation of All Words
*
* You are given a string, s, and a list of words, words, that are all of the same length.
* Find all starting indices of substring(s) in s that is a concatenation of each word in
* words exactly once and without any intervening characters.
*
* Example 1:
*
* Input:
* s = "barfoothefoobarman",
* words = ["foo","bar"]
* Output: [0,9]
*
* Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
* The output order does not matter, returning [9,0] is fine too.
*
* Example 2:
*
* Input:
* s = "wordgoodstudentgoodword",
* words = ["word","student"]
* Output: []
*/
/**
* @param {string} s
* @param {string[]} words
* @return {number[]}
*/
const findSubstring = (s, words) => {
// Sanity check
if (!words || words.length === 0) return [];
const m = words.length,
n = words[0].length,
len = m * n,
result = [];
// Build the word-count hash map
const map = {};
for (word of words) map[word] = ~~map[word] + 1;
// Try every possible start position i
for (let i = 0; i < s.length - len + 1; i++) {
// Make a copy of the hash map
const temp = Object.assign({}, map);
for (let j = i; j < i + len; j += n) {
const str = s.substr(j, n);
// Cannot find the word in hash map (words list), try another position
if (!(str in temp)) break;
// All the same word str are found, remove it from the hash map
if (--temp[str] === 0) delete temp[str];
}
// We have gone through the whole s and used all our words in the list
if (Object.keys(temp).length === 0) result.push(i);
}
return result;
};
export { findSubstring };