One Edit Distance

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

Solution

public class Solution {
     public boolean isOneEditDistance(String s, String t) {
        if (s == null || t == null) return false;

        int sizeS = s.length();
        int sizeT = t.length();

        for (int i = 0; i < Math.min(sizeS, sizeT); i++) {
            if (s.charAt(i) != t.charAt(i)) {
                if (sizeS == sizeT) {
                    return s.substring(i + 1).equals(t.substring(i + 1));
                } else if (sizeS < sizeT) {
                    return s.substring(i).equals(t.substring(i + 1));
                } else {
                    return s.substring(i + 1).equals(t.substring(i));
                }
            }
        }

        return Math.abs(sizeS - sizeT) == 1;
    }
}

results matching ""

    No results matching ""