1.5 One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away.
EXAMPLE
pale, pIe -> true
pales. pale -> true
pale. bale -> true
pale. bake -> false
public class Solution {
public static boolean canReplaceOneChar(String s, String t) {
int count = 0, len_s = s.length(), len_t = t.length();
for (int i = 0, j = 0; i < len_s && j < len_t; i++, j++) {
if (s.charAt(i) != t.charAt(j))
count++;
}
if (count != 1)
return false;
else
return true;
}
public static boolean canDeleteOneChar(String s, String t) {
int len_s = s.length(), len_t = t.length();
for (int i = 0, j = 0; i < len_s && j < len_t; i++, j++) {
if (s.charAt(i) != t.charAt(j)) {
return s.substring(i + 1).equals(t.substring(j));
}
}
return true;
}
public static boolean isOneEditDistance(String s, String t) {
if (s.equals(t))
return false;
int len_s = s.length(), len_t = t.length();
if (Math.abs(len_s - len_t) > 1)
return false;
if (len_s - len_t == 1) {
return canDeleteOneChar(s, t);
}
if (len_t - len_s == 1) {
return canDeleteOneChar(t, s);
}
if (len_s == len_t) {
return canReplaceOneChar(s, t);
}
return true;
}
}