Created
July 1, 2016 20:26
-
-
Save danielrobertson/657e777897d0be4fc0dfb51544d2655b to your computer and use it in GitHub Desktop.
Cracking the Coding Chpt 1.5 Is One Edit Away
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
// pale, ple -> true | |
// pales, pale -> true | |
// pale, bale -> true | |
// pale, bake -> false | |
boolean isOneAway(String a, String b) { | |
int aLength = a.length(); | |
int bLength = b.length(); | |
int shortIndex = 0; | |
int longIndex = 0; | |
if(Math.abs(aLength - bLength) > 1) { | |
return false; | |
} | |
String shorter = a.length() < b.length() ? a : b; | |
String longer = b.length() < b.length() ? b : a; | |
boolean foundEdit = false; | |
while(shortIndex < aLength && longIndex < bLength) { | |
if(shorter.charAt(shortIndex) != longer.charAt(longIndex)) { | |
if(foundEdit) { | |
return false; | |
} | |
foundEdit = true; | |
if(aLength == bLength) { | |
++shortIndex; | |
} | |
} | |
else { | |
// no edits | |
++longIndex; | |
} | |
++longIndex; | |
} | |
return true; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment