161. One Edit Distance

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

Solution:String

思路:
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) {
        for (int i = 0; i < Math.min(s.length(), t.length()); i++) { 
            if (s.charAt(i) != t.charAt(i)) {
                if (s.length() == t.length()) // s has the same length as t, so the only possibility is replacing one char in s and t
                    return s.substring(i + 1).equals(t.substring(i + 1));
                else if (s.length() < t.length()) // t is longer than s, so the only possibility is deleting one char from t
                    return s.substring(i).equals(t.substring(i + 1));               
                else // s is longer than t, so the only possibility is deleting one char from s
                    return t.substring(i).equals(s.substring(i + 1));
            }
        }       
        //All previous chars are the same, the only possibility is deleting the end char in the longer one of s and t 
        return Math.abs(s.length() - t.length()) == 1;        
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • Given two strings S and T, determine if they are both one...
    matrxyz閱讀 194評(píng)論 0 0
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,769評(píng)論 0 33
  • Given two strings S and T, determine if they are both one...
    Jeanz閱讀 216評(píng)論 0 0
  • 1.跪膝的好處: 跪膝補(bǔ)肝 膝為筋之府,肝為膝之府 跪膝為引血下行 養(yǎng)好肝,眼睛自然就更明亮啦 2.跪膝減肥 尤其...
    3ba44d9bd091閱讀 784評(píng)論 0 0
  • 2017.8.17 “舜初時(shí)致得象要?dú)⒓海嗍且蠛玫男奶保司褪撬粗^(guò)處。經(jīng)過(guò)來(lái),乃知功夫只在自己。不去責(zé)人,...
    官洪芹閱讀 257評(píng)論 0 0