-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path30.substring-with-concatenation-of-all-words.js
74 lines (67 loc) · 1.71 KB
/
30.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
65
66
67
68
69
70
71
72
73
74
/*
* @lc app=leetcode id=30 lang=javascript
*
* [30] Substring with Concatenation of All Words
*
* https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/
*
* algorithms
* Hard (22.63%)
* Total Accepted: 114.3K
* Total Submissions: 504.9K
* Testcase Example: '"barfoothefoobarman"\n["foo","bar"]'
*
* 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[]}
*/
function findSubstring(s, words) {
if (s.length === 0 || words.length === 0) return [];
const m = words[0].length,
n = words.length;
const wordsTotal = words.reduce((cntr, word) => ({
...cntr,
[word]: (cntr[word] || 0) + 1,
}),{});
const ans = [];
for (let i = 0; i < s.length - m * n + 1; i++) {
const wordsCntr = {};
let j;
for (j = 0; j < n; j++) {
const word = s.substr(i + j * m, m);
if (wordsTotal[word] === undefined) break;
wordsCntr[word] = (wordsCntr[word] || 0) + 1;
if (wordsCntr[word] > wordsTotal[word]) break;
}
if (j === n) ans.push(i);
}
return ans;
};