# Python ugly code (beg for improvements)

• The ugly code I admitted, but it was still accepted. The main idea of code is to check validation first and find the spilt site. After del the triplet site, the next step is do the recursion. When the board was empty, the solution was recorded.

class Solution(object):

``````def findMinStep(self, board, hand):
def firstcheck(board,hand):
# check ok parse or not
if board and not hand:
return -1
c = collections.Counter(board)
h = collections.Counter(hand)
for x,y in c.items():
if x in h:
if h[x] + y < 3: return -1
else:
if y < 3: return -1
return 1

def check(n_b,x):
# del triple site
if len(n_b) <= 2:
return n_b
elif n_b[x-1] == n_b[x]:
s = 0
while s < len(n_b) - 2:
if n_b[s] == n_b[s+1] and n_b[s+1] == n_b[s+2]:
while True:
if s != len(n_b)-1 and n_b[s] == n_b[s+1]: n_b = n_b[0:s] + n_b[s+1:]
else:  n_b = n_b[0:s] + n_b[s+1:]; break
s = 0
else:
s += 1
if len(n_b) < 3: return n_b
return n_b

def dfs(board,h):
# check if end?
if len(board) == 0:
k = len(h) if h else 0
print
self.final = max(k,self.final)
return
elif firstcheck(board,''.join(h)) != 1: return

# parse board and recurse
x = 0
while x <= len(board) - 1:
if board[x] in h:
x_h = h.index(board[x])
if  x< len(board) - 1  and board[x] == board[x+1]:
if x != len(board)-2 and x != 0:
dfs(check(board[0:x]+board[x+2:],x),h[0:x_h]+h[x_h+1:])
else:
dfs(board[0:x]+board[x+2:],h[0:x_h]+h[x_h+1:])
x += 1
else:
h.pop(x_h)
if board[x] in h:
h.pop(h.index(board[x]))
if x != len(board)-1 and x != 0:
dfs(check(board[0:x]+board[x+1:],x),h)
else:
dfs(board[0:x]+board[x+1:],h)
h.append(board[x])
h.append(board[x])
x += 1

if firstcheck(board,hand) != 1: return -1

self.final, self.n_h = -1, len(hand)
dfs(board,list(hand))

if self.final > -1: return len(hand) - self.final
else: return self.final``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.