Skip to content

Instantly share code, notes, and snippets.

@phyous
Created April 25, 2014 23:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phyous/11306226 to your computer and use it in GitHub Desktop.
Save phyous/11306226 to your computer and use it in GitHub Desktop.
public static boolean oneEditAppart(String a, String b) {
int edits = 0;
if (a == null || b == null || Math.abs(a.length() - b.length()) > 1) { // Strings more than 1 in size difference
return false;
} else if (a.length() == b.length()) { // Strings same size, check for 0 or >1 replacements
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) != b.charAt(i)) {
if (++edits > 1) return false;
}
}
if (edits == 0) return false;
} else { // if off by one, we can have an insertion or deletion. Check there is only 1
String large = a.length() > b.length() ? a : b;
String small = a.length() < b.length() ? a : b;
int i = 0;
while (i < small.length()) {
if (small.charAt(i) != large.charAt(i + edits)) {
if (++edits > 1)
return false;
} else {
i++;
}
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment