161. One Edit Distance
Last updated
Last updated
/**
* Time complexity : O(N) in the worst case when string lengths are close
* enough abs(ns - nt) <= 1, where N is a number of characters in the
* longest string. O(1) in the best case when abs(ns - nt) > 1.
* Space complexity : O(N) because strings are immutable in Python and Java
* and to create substring costs O(N) space.
*/
class Solution {
public boolean isOneEditDistance(String s, String t) {
int ns = s.length();
int nt = t.length();
// Ensure that s is shorter than t.
if (ns > nt)
return isOneEditDistance(t, s);
// The strings are NOT one edit away distance
// if the length diff is more than 1.
if (nt - ns > 1)
return false;
for (int i = 0; i < ns; i++)
if (s.charAt(i) != t.charAt(i))
// if strings have the same length
if (ns == nt)
return s.substring(i + 1).equals(t.substring(i + 1));
// if strings have different lengths
else
return s.substring(i).equals(t.substring(i + 1));
// If there is no diffs on ns distance
// the strings are one edit away only if
// t has one more character.
return (ns + 1 == nt);
}
}/**
* Time complexity : O(N)
* Space complexity : O(1)
*/
class Solution {
public boolean isOneEditDistance(String s, String t) {
if(s == null || t == null) return false;
int sLen = s.length(), tLen = t.length();
if(sLen == 0 && tLen == 0 || Math.abs(sLen-tLen) > 1) return false;
int i = 0, j = 0;
int diff = 0;
while(i < sLen && j < tLen) {
if(s.charAt(i) == t.charAt(j)) {
i++;
j++;
} else {
diff++;
if(diff > 1) return false;
if(sLen > tLen) {
i++;
} else if(sLen < tLen) {
j++;
} else {
i++;
j++;
}
}
}
if(i < sLen || j < tLen) diff++;
return diff == 1;
}
}