Last active
July 16, 2017 16:49
-
-
Save adleroliveira/f47e0e62f517689e4b1688ecff00bb87 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const findAnagramIndexes = (w1, w2) => { | |
let result = []; | |
let control = []; | |
for(let i = 0; i < w1.length; i++){ | |
if(control[i] === undefined) control[i] = w2.split(''); | |
for(let j = 0; j < control.length; j++) { | |
if(control[j] === null) continue; | |
if(Array.isArray(control[j]) && control[j].length === 0) continue; | |
let indexOfLetter = control[j].indexOf(w1[i]); | |
if(indexOfLetter > -1) { | |
control[j].splice(indexOfLetter, 1); | |
}else{ | |
control[j] = null; | |
} | |
if(Array.isArray(control[j]) && control[j].length === 0) { | |
result.push(j); | |
} | |
} | |
} | |
return result; | |
} | |
const findAnagramIndexes2 = (w1, w2) => { | |
const result = []; | |
const sum = str => str.split('').reduce((acc, x) => { | |
return acc + x.charCodeAt(0); | |
}, 0); | |
const haystack_len = w1.length; | |
const needle_len = w2.length; | |
const needle_sum = sum(w2); | |
for(let i=0; i<=(haystack_len - needle_len); i++){ | |
if(sum(w1.substr(i, needle_len)) === needle_sum) result.push(i) | |
} | |
return result; | |
} | |
console.log(findAnagramIndexes("aabcdfccbavncccab", "abc")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment