Given strings S and T, determine if they is both one edit distance apart.
Analysis: One edit distance, either s,t length is the same, only a pair of different char, then as long as you skip this pair of different char, you should be able to match two string;
Either the s,t length differs by one, the other parts match, and if you can match two strings, it returns true as long as you skip the mismatched character of the string with long length.
Time complexity: Just scan once, O (n)
public class Solution {public Boolean isoneeditdistance (string s, String t) { //make s to be the shorter string< C2/>if (S.length () > T.length ()) { return isoneeditdistance (t, s); } if (T.length ()-s.length () > 1) { return false; } int shift = T.length ()-s.length (); int i = 0; while (I < s.length () && s.charat (i) = = T.charat (i)) { i++; } if (shift = = 0) { i++; while (I < s.length () && s.charat (i) = = T.charat (i)) { i++; } return i = = S.length (); } else{ if (i = = S.length ()) { return true; } else{ while (I < s.length () && s.charat (i) = = T.charat (i + 1)) { i++; } return i = = S.length ();}}}
Observed again, in fact, the case of shift = = 1 is not necessary to discuss the if (i = = S.length ()), can be integrated into the following judgment, improve the following
public class Solution {public Boolean isoneeditdistance (string s, String t) { //make s to be the shorter string< C2/>if (S.length () > T.length ()) { return isoneeditdistance (t, s); } if (T.length ()-s.length () > 1) { return false; } int shift = T.length ()-s.length (); int i = 0; while (I < s.length () && s.charat (i) = = T.charat (i)) { i++; } if (shift = = 0) { i++; while (I < s.length () && s.charat (i) = = T.charat (i)) { i++; } return i = = S.length (); } else{ while (I < s.length () && s.charat (i) = = T.charat (i + 1)) { i++; } return i = = S.length ();}} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
#leetcode #one Edit Distance