More:【目錄】LeetCode Java實現html
Given two strings S and T, determine if they are both one edit distance apart.java
同時遍歷比較S和T的字符,直至遇到不一樣的字符:若是S和T的字符個數相同時,跳過不一樣的那個字符,繼續遍歷;若是S和T的字符個數相差爲1時,跳過較長的字符串的當天字符,繼續遍歷。若是剩下的字符都相等,那麼返回true,其他狀況爲false。post
public boolean isOneEditDistance(String s, String t) { if(s==null || t==null) return false; if(s.length()<t.length()) return isOneEditDistance(t, s); //學會交換 int i=0; while(i<t.length() && s.charAt(i)==t.charAt(i)) //注意i小於較短字符串的長度 i++; if(s.length()==t.length()) { i++; while(i<t.length() && s.charAt(i)==t.charAt(i)) i++; }else if(s.length()-t.length()==1){ while(i<t.length() && s.charAt(i+1)==t.charAt(i)) i++; }else return false; return i==t.length(); }
Time complexity : O(n)ui
Space complexity : O(1)htm
1. 代碼第5行,學會交換,僅須要實現S字符串的長度大於T字符串的狀況。blog
More:【目錄】LeetCode Java實現ip