forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
25 lines (24 loc) · 853 Bytes
/
Solution.py
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
class Solution:
def findMinStep(self, board: str, hand: str) -> int:
def remove(s):
while len(s):
next = re.sub(r'B{3,}|G{3,}|R{3,}|W{3,}|Y{3,}', '', s)
if len(next) == len(s):
break
s = next
return s
visited = set()
q = deque([(board, hand)])
while q:
state, balls = q.popleft()
if not state:
return len(hand) - len(balls)
for ball in set(balls):
b = balls.replace(ball, '', 1)
for i in range(1, len(state) + 1):
s = state[:i] + ball + state[i:]
s = remove(s)
if s not in visited:
visited.add(s)
q.append((s, b))
return -1