Given two strings S and T, determine if they are both one edit distance apart.算法
Hint:
1. If | n – m | is greater than 1, we know immediately both are not one-edit distance apart.
2. It might help if you consider these cases separately, m == n and m ≠ n.
3. Assume that m is always ≤ n, which greatly simplifies the conditional statements. If m > n, we could just simply swap S and T.
4. If m == n, it becomes finding if there is exactly one modified operation. If m ≠ n, you do not have to consider the delete operation. Just consider the insert operation in T.ide
ref from 達達spa
感受好聰明的解法,關鍵仍是corner case的嚴謹性code
http://www.danielbit.com/blog/puzzle/leetcode/leetcode-one-edit-distanceblog
「ip
[分析]
最笨的方法就是用Edit Distance算法,其實就是本身以前搞的生物信息學裏面的Needleman-Wunsch算法。孤陋寡聞了,搜了一下發現Edit Distance算法是DP的經典題。。。leetcode
這個題目只要O(1)的空間,O(n)的時間複雜度。假定有一下幾種狀況
1)修改一個字符(假定兩個String等長)
2)插入一個字符(中間或者結尾)string
[注意事項]
1)shift變量的做用it
」io
code也copy自人家
public class Solution { public boolean isOneEditDistance(String s, String t) { int m = s.length(), n = t.length(); if (m>n) return isOneEditDistance(t, s); if (n-m>1) return false; int i =0, shift = n-m; while (i<m && s.charAt(i)==t.charAt(i)) ++i; if (i==m) return shift > 0; // if two string are the same (shift==0), return false if (shift==0) i++; // if n==m skip current char in s (modify operation in s) while (i<m && s.charAt(i)==t.charAt(i+shift)) i++; // use shift to skip one char in t return i == m; } }