Last active
August 28, 2018 07:38
-
-
Save lienista/08a8a2dd3875051610c0ee640a433b7e to your computer and use it in GitHub Desktop.
Algorithms in Javascript: CTCI 1.5 One Away: Given 2 strings, determine if they differ from each other by a single character, either via insertion, deletion or replacement of a character.
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 isDifferByOne = (s1, s2) => { | |
| if(s1.length > s2.length + 1 || | |
| s2.length > s1.length + 1) { | |
| return false; | |
| } | |
| let count = 0; | |
| let charMap = new Map(); | |
| let a1 = s1.split(''); | |
| let a2 = s2.split(''); | |
| const len = a1.length > a2.length ? a1.length : a2.length; | |
| for(let i=0; i < len; i++){ | |
| charMap.set(s1[i], 1); | |
| let whichIndex = a2.indexOf(s1[i]); | |
| if(whichIndex >=0) { | |
| charMap.delete(s1[i]); | |
| a1.splice(whichIndex, 1); | |
| a2.splice(whichIndex, 1); | |
| } else { | |
| charMap.set(s2[i], 1); | |
| count++; | |
| } | |
| } | |
| return count === 1; | |
| } | |
| let a = 'abbc', | |
| b = 'abbcd'; | |
| console.log(isDifferByOne(a, b)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment