Leetcode-One Edit Distance

LiBlog發表於2016-08-29

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

Solution 1:

 1 public class Solution {
 2     public boolean isOneEditDistance(String s, String t) {
 3         if ((s.isEmpty() && t.isEmpty()) || Math.abs(s.length() - t.length()) > 1)
 4             return false;
 5 
 6         if (s.length() == t.length()) {
 7             return isOneReplace(s, t);
 8         }
 9 
10         if (s.length() > t.length()) {
11             return isOneInsert(t, s);
12         } else {
13             return isOneInsert(s, t);
14         }
15     }
16 
17     public boolean isOneReplace(String s, String t) {
18         boolean foundDiff = false;
19         for (int i = 0; i < s.length(); i++)
20             if (s.charAt(i) != t.charAt(i)) {
21                 if (foundDiff)
22                     return false;
23                 foundDiff = true;
24             }
25         return foundDiff;
26 
27     }
28 
29     public boolean isOneInsert(String small, String large) {
30         boolean hasSkip = false;
31         int p1 = 0, p2 = 0;
32         while (p1 < small.length() && p2 < large.length()) {
33             if (small.charAt(p1) != large.charAt(p2)) {
34                 if (hasSkip)
35                     return false;
36                 hasSkip = true;
37                 p2++;
38             } else {
39                 p1++;
40                 p2++;
41             }
42         }
43         return true;
44     }
45 }

NOTE: this solution is too much for this question. We can simply fetch substring and compare.

Solution 2:

 1 public class Solution {
 2     public boolean isOneEditDistance(String s, String t) {
 3         int m = s.length();
 4         int n = t.length();
 5         if (Math.abs(m - n) > 1) {
 6             return false;
 7         }
 8 
 9         int len = Math.min(m, n);
10         for (int i = 0; i < len; i++) {
11             if (s.charAt(i) != t.charAt(i)) {
12                 boolean result = s.substring(i).equals(t.substring(i + 1));
13                 result = result || s.substring(i + 1).equals(t.substring(i));
14                 result = result || s.substring(i + 1).equals(t.substring(i + 1));
15                 return result;
16             }
17         }
18         return Math.abs(m - n) == 1;
19     }
20 }

 

相關文章