This method uses a stack data structure. stack append and stack pop.
For each screened letter, it compares two distances.
My ugly solution — faster than 71.17%
My solution avoid most of the meaningless calculation in the most simple one, so it’s a litter bit faster.
The main point of my solution is to generate an interval defined by left and right. We have to screen string list used enumerate from left to right. index points to where we are, if we are in the interval, we have to compare distance to left and right; if not, we have to redefined left and right, then compare.
So for every letter, there are only two distances waiting to be calculated and compared.
classSolution: defshortestToChar(self, S, C): """ :type S: str :type C: str :rtype: List[int] """ listEqC =  for index, obj in enumerate(S): if obj == C: listEqC.append(index) return_list =  pointer = 0 if listEqC != : left = right = listEqC[pointer] else: left = right = float('inf') for index, obj in enumerate(S): if index >= right and pointer != len(listEqC)-1: pointer += 1 left = right right = listEqC[pointer] left_distance = abs(index-left) right_distance = abs(index-right) return_list.append(min(left_distance, right_distance)) return return_list