Clean recursive and iterative solutions


  • 1
    Y

    I start with the recursive solution as it is easier for me to think. The idea is find the first character that not equal to each other in s and t, we can either replace that character or delete the one in t. if(m > n) return isOneEditDistance(t, s); makes sure that s has less than or equal length to t.

    Since it is a tail recursion, it is very easy to change to an iterative solution. I used a for loop to find the first character that doesn't match and compare the substring for possible replace or deletion.

    // recursive
    public class Solution {
        public boolean isOneEditDistance(String s, String t) {
            int m = s.length();
            int n = t.length();
            if(m > n) {
                return isOneEditDistance(t, s);
            }
            if(n > m + 1) {
                return false;
            }
            if(m == 0) {
                return n == 1;
            }
            if(s.charAt(0) != t.charAt(0)) {
                return s.substring(1).equals(t.substring(1)) || s.equals(t.substring(1));
            }
            return isOneEditDistance(s.substring(1), t.substring(1));
        }
    }
    
    // iterative
    public class Solution {
        public boolean isOneEditDistance(String s, String t) {
            int m = s.length();
            int n = t.length();
            if(m > n) {
                return isOneEditDistance(t, s);
            }
            if(n > m + 1) {
                return false;
            }
            for(int i = 0; i < m; i++) {
                if(s.charAt(i) != t.charAt(i)) {
                    return s.substring(i+1).equals(t.substring(i+1)) || s.substring(i).equals(t.substring(i+1));
                }
            }
            return m == n - 1;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.