[LintCode] Edit Distance II
Given two strings S and T, determine if they are both one edit distance apart. There are three types of
edits that can be performed on strings: insert a character, remove a character, or replace a character.
Given s = "aDb"
, t = "adb"
return true
If s is one insertion apart from t, then t is one deletion apart from s as insertion and deletion are reverse
operations. So we simplify the original problem to given two strings smaller and bigger, with smaller's length
less than or equal to bigger's length, check if smaller is one insertion or replace apart from bigger.
Algorithm:
1. From the start of both strings, compare each character. If equal, increment both index pointers by 1;
2. If not equal: increment the difference count by 1, if this count is > 1, return false;
if the two strings have the same length, then this difference is the only replace that should
happen, increment both index pointers and expect no more differences.
if they don't have the same length, then it means this difference is where an insertion could happen
to make them equal. Only increment bigger's index pointer and expect no more differences.
Runtime: O(smaller string's length)
1 public class Solution { 2 /** 3 * @param s a string 4 * @param t a string 5 * @return true if they are both one edit distance apart or false 6 */ 7 public boolean isOneEditDistance(String s, String t) { 8 if(s == null || t == null || Math.abs(s.length() - t.length()) > 1){ 9 return false; 10 } 11 String smaller = s.length() <= t.length() ? s : t; 12 String bigger = s.length() > t.length() ? s : t; 13 int smallerIdx = 0, biggerIdx = 0; 14 int diffCnt = 0; 15 while(smallerIdx < smaller.length()){ 16 if(smaller.charAt(smallerIdx) != bigger.charAt(biggerIdx)){ 17 diffCnt++; 18 if(diffCnt > 1){ 19 return false; 20 } 21 if(smaller.length() == bigger.length()){ 22 smallerIdx++; 23 biggerIdx++; 24 } 25 else{ 26 biggerIdx++; 27 } 28 } 29 else{ 30 smallerIdx++; 31 biggerIdx++; 32 } 33 } 34 if(smaller.length() == bigger.length() && diffCnt == 0){ 35 return false; 36 } 37 return true; 38 } 39 }
Related Problems