题目:
Given two strings S and T, determine if they are both one edit distance apart
i. Modify operation – Modify a character to X in S.
S = “abcde”
T = “abXde”
ii. Insert operation – X was inserted before a character in S.
S = “abcde”
T = “abcXde”
iii. Append operation – X was appended at the end of S.
S = “abcde”
T = “abcdeX”
解答:
1 public class Solution { 2 3 public static void main(String[] args) { 4 String s = "abcde"; 5 String t = "abcdeX"; 6 7 System.out.println(isOneEditDistance(s, t)); 8 } 9 10 public boolean isOneEditDistance(String s, String t) { 11 int m = s.length(); 12 int n = t.length(); 13 if(m > n) { 14 return isOneEditDistance(t, s); 15 } 16 17 if(n - m > 1) { 18 return flase; 19 } 20 21 int i = 0; 22 shift = n - m; 23 while(i < m && s.charAt(i) == t.charAt(i)) { 24 i++; 25 } 26 27 if(i == m) { 28 return shift > 0; 29 } 30 31 if(shift == 0) { 32 i++; 33 } 34 35 while(i < m && s.charAt(i) == t.charAt(i+shift)) { 36 i++; 37 } 38 39 return i == m; 40 } 41 42 }