Skip to content

Instantly share code, notes, and snippets.

@p8ul
Created June 26, 2019 08:25
Show Gist options
  • Save p8ul/162fd5005b718682ccc1ae618d864bb2 to your computer and use it in GitHub Desktop.
Save p8ul/162fd5005b718682ccc1ae618d864bb2 to your computer and use it in GitHub Desktop.
Search through a string using sliding window algorithm.
/*
Sliding window involves creating a window which can either be an array or number from one
position to another.
Depending on a certain condition, the window either increases or closes (and new window is created)
Very uselful for keeping track of subset of data in an array/string etc.
*/
/**
* @desc The function find substring in a string and return number of times the substring is found using sliding window algorithm
* @param {String} longString Where to search a substring
* @param {String} shortString The substring to be looked up
*
* @returns {Number} number of found instances of shortString *
*/
function search(longString, shortString) {
let currentSubString = '';
let counter = 0;
if (shortString > longString.length) return null;
for (let i = 0; i < shortString.length; i ++) {
currentSubString += longString[i]; // Get the first n (length of substring) characters from a longString: Hel
}
// check whether the first n (length of substring) characters of the longString is equal to shortString and increment the counter
if (currentSubString === shortString) {
counter++;
}
for (let i = shortString.length; i < longString.length + 1; i ++) {
// Remove the first character and add the nth character:
// first loop: Hel => ell
currentSubString = currentSubString.substring(1) + longString[i]
// compare if the current substring is equal to short string:
// first loop: ell == lol
if (currentSubString === shortString) {
counter ++;
}
}
return counter;
}
search('Hello loled', 'lol')
// Native javascript search
function nativeSearch (long, short) {
var count = 0;
for (var i = 0; i < long.length; i++) {
for (var j = 0; j < short.length; j++) {
if (short[j] !== long[i+j]) break;
if (j === short.length - 1) count++;
}
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment