Skip to content

Commit e3b976b

Browse files
One Edit Distance: Accepted
1 parent 04a8587 commit e3b976b

2 files changed

Lines changed: 52 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,7 @@ My accepted leetcode solutions to some of the common interview problems.
201201
- [Permutation in String](problems/src/string/PermutationInString.java) (Medium)
202202
- [Add Binary](problems/src/string/AddBinary.java) (Easy)
203203
- [Valid Palindrome II](problems/src/string/ValidPalindromeII.java) (Easy)
204+
- [One Edit Distance](problems/src/string/OneEditDistance.java) (Medium)
204205

205206
#### [Tree](problems/src/tree)
206207

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package string;
2+
3+
/**
4+
* Created by gouthamvidyapradhan on 09/12/2017.
5+
*
6+
* Given two strings S and T, determine if they are both one edit distance apart.
7+
*/
8+
public class OneEditDistance {
9+
10+
/**
11+
* Main method
12+
* @param args
13+
* @throws Exception
14+
*/
15+
public static void main(String[] args) throws Exception{
16+
System.out.println(new OneEditDistance().isOneEditDistance("abxd", "adxb"));
17+
}
18+
19+
public boolean isOneEditDistance(String s, String t) {
20+
if(Math.abs(s.length() - t.length()) > 1 || s.equals(t)) return false;
21+
if(s.length() > t.length()){
22+
return hasDiffOne(s, t, false);
23+
} else if(t.length() > s.length()){
24+
return hasDiffOne(t, s, false);
25+
} else{
26+
return hasDiffOne(s, t, true);
27+
}
28+
}
29+
30+
private boolean hasDiffOne(String s, String t, boolean sameLength){
31+
int count = 0, i = 0, j = 0;
32+
for(int l1 = s.length(), l2 = t.length(); i < l1 && j < l2;){
33+
if(s.charAt(i) == t.charAt(j)){
34+
i++; j++;
35+
} else{
36+
if(count > 0) return false;
37+
count++;
38+
if(sameLength){
39+
i++; j++;
40+
} else{
41+
i++;
42+
}
43+
}
44+
}
45+
if(i == j){
46+
return true;
47+
} else{
48+
return (s.charAt(s.length() - 1) == t.charAt(t.length() - 1));
49+
}
50+
}
51+
}

0 commit comments

Comments
 (0)