Skip to content

Instantly share code, notes, and snippets.

@danielrobertson
Created July 1, 2016 20:26
Show Gist options
  • Save danielrobertson/657e777897d0be4fc0dfb51544d2655b to your computer and use it in GitHub Desktop.
Save danielrobertson/657e777897d0be4fc0dfb51544d2655b to your computer and use it in GitHub Desktop.
Cracking the Coding Chpt 1.5 Is One Edit Away
// 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