Two pointer iterative solution


  • 0
    D
    public boolean isOneEditDistance(String s, String t) {
    
    	if (s == null && t == null) {
    		return false;
    	}
    
    	if (s.equals(t)) {
    		return false;
    	}
    
    	if (Math.abs(s.length() - t.length()) >= 2) {
    		return false;
    	}
    
    
    	int sLen = s.length();
    	int tLen = t.length();
    
    	int i = 0;
    	int j = 0;
    	int count = 0;
    	while (i < sLen && j < tLen) {
    		if (s.charAt(i) == t.charAt(j)) {
    			i++;
    			j++;
    		} else {
    			count++;
    			if (count >= 2) {
    				return false;
    			}
    
    			// check if an insertion may fix the problem
    			if (sLen	< tLen) {
    				j++;
    			} else if (sLen > tLen) {
    				i++;
    			} else {
    				i++;
    				j++;
    			}
    
    		}
    	}
    	// check for conditions like "abc" & "abcd" (insertion in between, count = 1), 
    	// "abd" & "abcd" (insertion at the end, count = 0)
    	if (count <= 1) {
    		return true;
    	}
    
    	return false;
    }

Log in to reply
 

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