File tree Expand file tree Collapse file tree 1 file changed +34
-45
lines changed Expand file tree Collapse file tree 1 file changed +34
-45
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
- public static boolean isOneEditDistance (String s , String t ) {
3
- if (Math .abs (s .length () - t .length ()) > 1 ) {
4
- return false ;
5
- }
6
- else if (s .length () - t .length () == 0 ) {
7
- if (s .equals (t )) {
8
- return false ;
9
- }
10
-
11
- boolean missed = false ;
12
- for (int i =0 ; i <s .length (); i ++) {
13
- if (s .charAt (i ) == t .charAt (i )) {
14
- continue ;
15
- }
16
- if (missed ) {
17
- return false ;
18
- }
19
-
20
- missed = true ;
21
- }
22
- return true ;
23
- }
24
-
25
- return s .length () - t .length () == 1 ? oneDeleteOnly (s ,t ) : oneDeleteOnly (t ,s );
2
+ public boolean isOneEditDistance (String s , String t ) {
3
+ int lengthDiff = Math .abs (s .length () - t .length ());
4
+ if (s .equals (t ) || lengthDiff > 1 ) {
5
+ return false ;
26
6
}
27
-
28
- private static boolean oneDeleteOnly (String s , String t ) {
29
- if (t .length () == 0 ) {
30
- return true ;
31
- }
32
- int i = 0 ;
33
- int j = 0 ;
34
-
35
- while (i < s .length () && j < t .length ()) {
36
- if (s .charAt (i ) != t .charAt (j )) {
37
- if (i > j ) {
38
- return false ;
39
- }
40
- i ++;
41
- continue ;
42
- }
43
-
44
- i ++;
45
- j ++;
7
+ if (s .length () == 0 || t .length () == 0 ) {
8
+ return true ;
9
+ }
10
+ int idxOne = 0 ;
11
+ int idxTwo = 0 ;
12
+ boolean changeDone = false ;
13
+ while (idxOne < s .length () && idxTwo < t .length ()) {
14
+ if (s .charAt (idxOne ) == t .charAt (idxTwo )) {
15
+ idxOne ++;
16
+ idxTwo ++;
17
+ continue ;
18
+ }
19
+ if (changeDone ) {
20
+ return false ;
21
+ }
22
+ if (lengthDiff != 0 ) {
23
+ if (s .length () > t .length ()) {
24
+ idxOne ++;
25
+ } else {
26
+ idxTwo ++;
46
27
}
47
-
48
- return true ;
28
+ } else {
29
+ idxOne ++;
30
+ idxTwo ++;
31
+ }
32
+ changeDone = true ;
33
+ }
34
+ if (changeDone && (idxOne != s .length () || idxTwo != t .length ())) {
35
+ return false ;
49
36
}
37
+ return true ;
38
+ }
50
39
}
You can’t perform that action at this time.
0 commit comments