Skip to content

Commit 4328a1c

Browse files
committedJan 12, 2023
Add solution #30
1 parent 98e761e commit 4328a1c

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
 

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
27|[Remove Element](./0027-remove-element.js)|Easy|
3636
28|[Implement strStr()](./0028-implement-strstr.js)|Easy|
3737
29|[Divide Two Integers](./0029-divide-two-integers.js)|Medium|
38+
30|[Substring with Concatenation of All Words](./0030-substring-with-concatenation-of-all-words.js)|Hard|
3839
31|[Next Permutation](./0031-next-permutation.js)|Medium|
3940
33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium|
4041
34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* 30. Substring with Concatenation of All Words
3+
* https://leetcode.com/problems/substring-with-concatenation-of-all-words/
4+
* Difficulty: Hard
5+
*
6+
* You are given a string s and an array of strings words. All the strings of words are of the same
7+
* length.
8+
*
9+
* A concatenated substring in s is a substring that contains all the strings of any permutation of
10+
* words concatenated.
11+
*
12+
* - For example, if words = ["ab","cd","ef"], then "abcdef", "abefcd", "cdabef", "cdefab", "efabcd",
13+
* and "efcdab" are all concatenated strings. "acdbef" is not a concatenated substring because it is
14+
* not the concatenation of any permutation of words.
15+
*
16+
* Return the starting indices of all the concatenated substrings in s. You can return the answer in
17+
* any order.
18+
*/
19+
20+
/**
21+
* @param {string} s
22+
* @param {string[]} words
23+
* @return {number[]}
24+
*/
25+
var findSubstring = function(s, words) {
26+
if (!words || words.length === 0) {
27+
return [];
28+
}
29+
30+
const result = [];
31+
const map = {};
32+
const count = words[0].length;
33+
34+
words.forEach(word => map[word] = ~~map[word] + 1);
35+
36+
for (let i = 0; i < s.length - words.length * count + 1; i++) {
37+
const temp = Object.assign({}, map);
38+
39+
for (let j = i; j < i + words.length * count; j += count) {
40+
const key = s.slice(j, j + count);
41+
if (!temp[key]) {
42+
break;
43+
} else if (--temp[key] === 0) {
44+
delete temp[key];
45+
}
46+
}
47+
48+
if (Object.keys(temp).length === 0) {
49+
result.push(i);
50+
}
51+
}
52+
53+
return result;
54+
};

0 commit comments

Comments
 (0)
Please sign in to comment.