Java Solution with O(1) Space and O(n) time beat 93%


  • 0
    L
    class Solution {
        public boolean isOneEditDistance(String s, String t) {
            int m = s.length();
            int n = t.length();
            
                    
            if(s.equals(t)) {
                return false;
            }
            
            if(m < n) {
                return isOneEditDistance(t, s);
            }
    
            int i = 0;
            int j = 0;
            while(i < m && j < n && s.charAt(i) == t.charAt(j)) {
                i++;
                j++;
            }
            if(j == n) {// first n char are same
                return m == n + 1;
            } else {//  ecounter one different char
                if(m == n) {
                    j++;
                }
                i++;
            }
            while(i < m && j < n) {
                if(s.charAt(i) != t.charAt(j)) {
                    return false;
                }
                i++;
                j++;
            }
            return (m == n) || (m == n + 1);
        }
    }
    

Log in to reply
 

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