Given two strings S and T, determine if they are both one edit distance apart.
注意这道题:Must be exactly one distance apart. Not the same.
public boolean isOneEditDistance(String s, String t) {
for (int i=0; i<Math.min(s.length(), t.length()); i++) {
if (s.charAt(i) != t.charAt(i)) {
if (s.length() == t.length())
return s.substring(i+1).equals(t.substring(i+1));
else if (s.length() < t.length()) {
return s.substring(i).equals(t.substring(i+1));
}
else return t.substring(i).equals(s.substring(i+1));
}
}
//Corner case, last char
return Math.abs(s.length() - t.length()) == 1;
}
}
另外FB面经有一道比较狠的这个题的变形:
class IntFileIterator { boolean hasNext(); int next(); } class{ public boolean isDistanceZeroOrOne(IntFileIterator a, IntFileIterator b); } // return if the distance between a and b is at most 1.. // Distance: minimum number of modifications to make a=b // Modification: // 1. change an int in a // 2. insert an int to a // 3. remove an int from a
这题就是one edit distance的变形题,难点在于给的Iterator,事先不知道两个file
的长度,也不允许用extra space(所以不能转成两个string再比),那么一个个往前
跑的时候就得三种情况都考虑。。。。
我的做法
public class Solution {
class IntFileIterator {
boolean hasNext();
int next();
}
public boolean isDistanceZeroOrOne(IntFileIterator a, IntFileIterator b) {
return check(a, b, 0);
}
public boolean check(IntFileIterator a, IntFileIterator b, int distance){
IntFileIterator aa = new InFileIterator(a); // copy of iterator a before next() function
IntFileIterator bb = new InFileIterator(b);
while (a.hasNext() && b.hasNext()) {
int s = a.next();
int t = b.next();
if(s != t){
IntFileIterator aaa = new InFileIterator(a); //copy of iterator a after next() function
IntFileIterator bbb = new InFileIterator(b);
distance++;
if(distance>1) return false;
return check(aa, b, distance) || check(a, bb, distance) || check(aaa, bbb, distance);
}
else{
return check(a, b, distance);
}
}
if(distance == 1){
return !a.hasNext() && !b.hasNext();
}else { //(distance ==0)
IntFileIterator k = a.hasNext()? a : b;
int count = 0;
while (k.hasNext()) {
k.next();
count++;
}
return count<=1;
}
}
}