Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 125bdff

Browse files
substring-with-concatenation-of-all-words
1 parent 6432946 commit 125bdff

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Substring with Concatenation of All Words
2+
3+
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.
4+
5+
## Example 1
6+
7+
Input:
8+
9+
s = "barfoothefoobarman", words = ["foo","bar"]
10+
11+
Output: [0,9]
12+
13+
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
14+
The output order does not matter, returning [9,0] is fine too.
15+
16+
## Example 2
17+
18+
Input:
19+
20+
s = "wordgoodgoodgoodbestword",
21+
22+
words = ["word","good","best","word"]
23+
24+
Output: []
25+
26+
## More info
27+
28+
<https://leetcode.com/problems/substring-with-concatenation-of-all-words/>
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {string} s
3+
* @param {string[]} words
4+
* @return {number[]}
5+
*/
6+
var findSubstring = function (s, words) {
7+
if (!words || words.length === 0) return [];
8+
9+
let uniqueWordsMap = {};
10+
let n = words.length, m = words[0].length;
11+
let len = n * m;
12+
let resp = [];
13+
for (word of words) uniqueWordsMap[word] = ~~uniqueWordsMap[word] + 1;
14+
for (let i = 0; i < s.length - len + 1; i++) {
15+
let temp = Object.assign({}, uniqueWordsMap);
16+
for (let j = i; j < i + len; j += m) {
17+
const str = s.substr(j, m);
18+
if (!(str in temp)) break;
19+
if (--temp[str] === 0) delete temp[str];
20+
}
21+
if (Object.keys(temp).length === 0) resp.push(i);
22+
}
23+
return resp;
24+
};
25+
26+
console.log(findSubstring("", []))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /