This is the solution about Leetcode - One Edit Distance.

Description

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

Solution

Analysis

Solution

  1. In order to compare easily, be sure the longer string first.
  2. When find out the different character, compare their remaining string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
public boolean isOneEditDistance(String s, String t) {
if(s.length() < t.length()) {
return isOneEditDistance(t,s);
}
int i = 0;
while(i < t.length()) {
if(s.charAt(i) != t.charAt(i)) {
if(s.length() == t.length()) {
return s.substring(i+1).equals(t.substring(i+1));
}else {
return s.substring(i+1).equals(t.substring(i));
}
}
i++;
}
//prevent s is longer than t by 1 character
return i==(s.length()-1);
}
}