161. One Edit Distance

Given two strings S and T, determine if they are both one edit distance apart.

Solution:

思路:
A = "1 2 3 4 5"
B = "1 2 3 4 5"
One Edit Check三種情況即可:
(1)delete one char in A,(2)delete one char in B, (3)replace one char in A
InsertA和deleteB效果相同
Time Complexity: O(N) Space Complexity: O(1)

Solution Code:

class Solution {
 /*
 * There're 3 possibilities to satisfy one edit distance apart: 
 * 
 * 1) Replace 1 char:
      s: a B c
      t: a D c
 * 2) Delete 1 char from s: 
      s: a D  b c
      t: a    b c
 * 3) Delete 1 char from t
      s: a   b c
      t: a D b c
 */
    public boolean isOneEditDistance(String s, String t) {
        int len = Math.min(s.length(), t.length());
        for(int c = 0; c < len; c++) {
            if(s.charAt(c) != t.charAt(c)) {
                // try if replacing works
                if(s.length() == t.length()) return s.substring(c + 1).equals(t.substring(c + 1));
                else {
                    // try if deleting works 
                    if(s.length() > t.length()) return t.substring(c).equals(s.substring(c + 1));  //delete from s
                    else return s.substring(c).equals(t.substring(c + 1));  //delete from t
                }
            }
        }
        //All previous chars checked are the same, then check if the diff of lenth for the rest is one
        return Math.abs(s.length() - t.length()) == 1;
    }
}
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容