@@ -109,30 +109,27 @@ class Solution {
109
109
代码:
110
110
``` Java
111
111
class Solution {
112
- String S , T ;
112
+ static char [] items = new char []{ ' A ' , ' C ' , ' G ' , ' T ' } ;
113
113
Set<String > set = new HashSet<> ();
114
- static char [] items = new char []{' A' ,' C' ,' G' ,' T' };
115
- public int minMutation (String _s , String _e , String [] bank ) {
116
- S = _s; T = _e;
114
+ public int minMutation (String S , String T , String [] bank ) {
115
+ set. add(S );
117
116
for (String s : bank) set. add(s);
118
- return bfs();
119
- }
120
- int bfs () {
117
+ if (! set. contains(T )) return - 1 ;
121
118
Deque<String > d1 = new ArrayDeque<> (), d2 = new ArrayDeque<> ();
119
+ d1. addLast(S ); d2. addLast(T );
122
120
Map<String , Integer > m1 = new HashMap<> (), m2 = new HashMap<> ();
123
- d1. addLast(S ); m1. put(S , 0 );
124
- d2. addLast(T ); m2. put(T , 0 );
121
+ m1. put(S , 0 ); m2. put(T , 0 );
125
122
while (! d1. isEmpty() && ! d2. isEmpty()) {
126
123
int t = - 1 ;
127
- if (d1. size() <= d2. size()) t = update(d1, m1, m2);
124
+ if (d1. size() <= d2. size()) t = update(d1, m1, m2);
128
125
else t = update(d2, m2, m1);
129
126
if (t != - 1 ) return t;
130
127
}
131
128
return - 1 ;
132
129
}
133
130
int update (Deque<String > d , Map<String , Integer > cur , Map<String , Integer > other ) {
134
- int size = d. size();
135
- while (size -- > 0 ) {
131
+ int m = d. size();
132
+ while (m -- > 0 ) {
136
133
String s = d. pollFirst();
137
134
char [] cs = s. toCharArray();
138
135
int step = cur. get(s);
@@ -142,12 +139,10 @@ class Solution {
142
139
char [] clone = cs. clone();
143
140
clone[i] = c;
144
141
String sub = String . valueOf(clone);
145
- if (! set. contains(sub)) continue ;
146
- if (other. containsKey(sub)) return step + 1 + other. get(sub);
147
- if (! cur. containsKey(sub) || cur. get(sub) > step + 1 ) {
148
- cur. put(sub, step + 1 );
149
- d. addLast(sub);
150
- }
142
+ if (! set. contains(sub) || cur. containsKey(sub)) continue ;
143
+ if (other. containsKey(sub)) return other. get(sub) + step + 1 ;
144
+ d. addLast(sub);
145
+ cur. put(sub, step + 1 );
151
146
}
152
147
}
153
148
}
0 commit comments