Python,112字节
d=lambda x,l,h:0if h<l else d(x,l+1,h-1)if x[l]==x[h]else-~min(d(x,l+1,h),d(x,l,h-1));e=lambda x:d(x,0,len(x)-1)
效率很低。
在线尝试!您必须等待一分钟,以完成最后一个案例。
用调用e(<string>, 0, <length of string - 1>),例如e(“ fishes”,0,5)`。
松散的(某种)解释:
def minInsert(x, l, h): # Declare func, arugments for x, l, h # d=lambda x,l,h:
if l >= h: # If l is the same or past h # if h<l
return 0 # then return 0 # 0
elif x[l] == x[h]: # If first and last character are the same # else if x[l]==x[h]
return minInsert(x, l + 1, h - 1) # then return the min w/o first & last # d(x,l+1,h-1)
else: # If not, we shave off a character # else
a = minInsert(x, l, h - 1) # (last one) # d(x,l+1,h)
b = minInsert(x, l + 1, h) # (first one) # d(x,l,h-1)
return min(a, b) + 1 # and add one for the char we took off # -~min( , )