Share my Java AC solution, O(1) space, one for-loop, no string concatenation


  • 0
    J
    public class Solution {
    	public boolean isOneEditDistance(String s, String t) {
    		int m = s.length(), n = t.length();
    		if (m > n)	// s is the shorter one
    			return isOneEditDistance(t, s);
    		if (m + 1 < n)
    			return false;
    		
    		int count = 0;
    		for (int i = 0, j = 0; j < n; i++, j++) {
    		    if (i == m) {
    		        count++;
    		        continue;
    		    }
    			if (s.charAt(i) == t.charAt(j))
    				continue;
    			count ^= 1;
    			if (count == 0)
    				return false;		
    			if (m < n)
    				i--;
    		}
    		return count == 1;
    	}
    }

Log in to reply
 

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