Given two strings S and T, determine if they are both one edit distance apart.
One ediit distance means doing one of these operation:
insert one character in any position of S
delete one character in S
change one character in S to other character
Example
Example 1:
Input: s = "aDb", t = "adb"
Output: true
Example 2:
Input: s = "ab", t = "ab"
Output: false
Explanation:
s=t ,so they aren't one edit distance apart
publicclassSolution {publicbooleanisOneEditDistance(String s1,String s2) {int m =s1.length(), n =s2.length();if (Math.abs(m - n) >1)returnfalse;int count =0; // Count of editsint i =0, j =0;while (i < m && j < n) {// If current characters don't matchif (s1.charAt(i) !=s2.charAt(j)) {if (count ==1)returnfalse;// If length of one string is more, then possible edits// are 1-> Add a character 2-> Remove a character// If we add to smaller string OR remove from bigger string// in both the cases the pointer of bigger string needs to moveif (m > n) i++;elseif (m < n) j++;// If m==n, then only possible edit is to replace char// In this both the pointers will move aheadelse { i++; j++; }// Increment count of edits count++; } else { i++; j++; } }// If we reach here and m & n have not reached full lengths// That means the strings are equal upto min(m,n) (maybe with 1 edit already)// So now to make these 2 equals, we can add the extra char to smaller stringif (i < m || j < n) count++;return count ==1; }}