/**
* @param {string} s
* @param {string[]} words
* @return {number[]}
*/
var findSubstring = function(s, words) {
var hash = {};
var wordLength = words[0].length;
var wordsTotal = wordLength * words.length;
for (const word of words) {
if (hash[word]) {
hash[word]++;
} else {
hash[word] = 1;
}
}
var slidingWindow = [];
var sol = [];
for(var i = 0; i < s.length ; i++) {
if (slidingWindow.length < wordsTotal - 1) {
slidingWindow.push(s[i]);
} else {
slidingWindow.push(s[i]);
if (isPermutationOfWords(slidingWindow.join(''), Object.assign({}, hash), wordLength)) {
sol.push(i - wordsTotal + 1);
}
slidingWindow.shift();
}
}
return sol;
};
function isPermutationOfWords(s, words, wordLength) {
var str = "";
for(var i = 0; i < s.length; i++) {
str += s[i];
if (str.length == wordLength) {
if (words[str]) {
words[str]--;
str = "";
} else {
return false;
}
}
}
return true;
}
No comments:
Post a Comment