One Edit Distance

Given two strings S and T, determine if they are both one edit distance apart.

Solution:

  1. public class Solution {
  2. public boolean isOneEditDistance(String s, String t) {
  3. if (s == null || t == null)
  4. return false;
  5. if (s.length() > t.length())
  6. return isOneEditDistance(t, s);
  7. int i = 0;
  8. while (i < s.length() && i < t.length()) {
  9. if (s.charAt(i) != t.charAt(i)) {
  10. return s.substring(i + 1).equals(t.substring(i + 1)) ||
  11. s.substring(i).equals(t.substring(i + 1));
  12. }
  13. i++;
  14. }
  15. return t.length() - i == 1;
  16. }
  17. }