Given two strings S and T, determine if they are both one edit distance apart.
注意這道題:Must be exactly one distance apart. Not the same.spa
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面經有一道比較狠的這個題的變形:code
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再比),那麼一個個往前
跑的時候就得三種狀況都考慮。。。。blog
個人作法rem
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; } } }