/
OneEditApart.java
60 lines (55 loc) · 1.69 KB
/
OneEditApart.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.interview.recursion;
/**
* Date 03/26/2016
* @author Tushar Roy
* Given two strings S and T, determine if they are both one edit distance apart.
*
* Time complexity O(n)
* Space complexity O(1)
*
* Reference
* https://leetcode.com/problems/one-edit-distance/
*/
public class OneEditApart {
public boolean isOneEditDistance(String s, String t) {
String larger, smaller;
if (s.length() < t.length()) {
larger = t;
smaller = s;
} else {
larger = s;
smaller = t;
}
if (Math.abs(larger.length() - smaller.length()) > 1) {
return false;
}
boolean diffFound = false;
int j = 0;
for (int i = 0; i < smaller.length();) {
if (smaller.charAt(i) == larger.charAt(j)) {
i++;
j++;
} else {
if (diffFound) {
return false;
} else {
diffFound = true;
if (smaller.length() == larger.length()) {
i++; j++;
} else {
j++;
}
}
}
}
return diffFound || j < larger.length();
}
public static void main(String args[]){
OneEditApart oea = new OneEditApart();
System.out.println(oea.isOneEditDistance("cat", "dog"));
System.out.println(oea.isOneEditDistance("cat", "cats"));
System.out.println(oea.isOneEditDistance("cat", "cut"));
System.out.println(oea.isOneEditDistance("cats", "casts"));
System.out.println(oea.isOneEditDistance("catsts", "casts"));
}
}