Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static boolean isOneEditAway(String str1, String str2) {
- if (str1 == null || str2 == null || Math.abs(str1.length() - str2.length()) > 1) {
- return false;
- }
- int lengthDiff = str1.length() - str2.length();
- int edits = 0;
- int i = 0, k = 0;
- for (; i < str1.length() && k < str2.length(); i++, k++) {
- char c1 = str1.charAt(i);
- char c2 = str2.charAt(k);
- if (c1 == c2) {
- continue;
- }
- edits++;
- if (edits > 1) {
- return false;
- }
- if (lengthDiff == 0) {
- continue;
- }
- if (lengthDiff == -1 && k != str2.length() - 1 && c1 == str2.charAt(k + 1)) {
- k++;
- } else if (lengthDiff == 1 && i != str1.length() - 1 && c2 == str1.charAt(i + 1)) {
- i++;
- }
- }
- edits += str1.length() - i;
- edits += str2.length() - k;
- return edits < 2;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement