给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。
示例 1:
输入: S = "loveleetcode", C = 'e'
输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
说明:
字符串 S 的长度范围为 [1, 10000]。
C 是一个单字符,且保证是字符串 S 里的字符。
S 和 C 中的所有字母均为小写字母。
class Solution: def shortestToChar(self, S: str, C: str) -> List[int]: n=len(S) res=[] c=[] for i in range(n): if S[i]==C: c.append(i) m=len(c) if m==1: if 0<c[0]<n-1: for i in range(c[0],-1,-1): res.append(i) for i in range(n-c[0]-1): res.append(i+1) elif c[0]==n-1: for i in range(c[0],-1,-1): res.append(i) else: for i in range(n): res.append(i) elif m==2: for i in range(c[0],-1,-1): res.append(i) if (c[1]-c[0])%2==1: for i in range(1,(c[1]-c[0])//2+1): res.append(i) for i in range((c[1]-c[0])//2,-1,-1): res.append(i) else: for i in range(1,(c[1]-c[0])//2+1): res.append(i) for i in range((c[1]-c[0])//2-1,-1,-1): res.append(i) for i in range(n-c[1]-1): res.append(i+1) else: for i in range(c[0],-1,-1): res.append(i) a=0 b=1 while b<=m-1: if (c[b]-c[a])%2==1: for i in range(1,(c[b]-c[a])//2+1): res.append(i) for i in range((c[b]-c[a])//2,-1,-1): res.append(i) else: for i in range(1,(c[b]-c[a])//2+1): res.append(i) for i in range((c[b]-c[a])//2-1,-1,-1): res.append(i) a+=1 b+=1 for i in range(n-c[-1]-1): res.append(i+1) return res
class Solution(object): def shortestToChar(self, S, C): pre = float('-inf') res = [] for i, x in enumerate(S): if x == C: pre = i res.append(i - pre) pre = float('inf') for i in range(len(S) - 1, -1, -1): if S[i] == C: pre = i res[i] = min(res[i], pre - i) return res
class Solution: def shortestToChar(self, S: str, C: str) -> List[int]: return [min(S.find(C, i)-i, i-S[:i+1].rfind(C)) if S[:i+1].rfind(C) != -1 and S.find(C, i) != -1 else S.find(C, i)-i if S[:i+1].rfind(C) == -1 else i-S[:i+1].rfind(C) for i in range(len(S))]
class Solution: def shortestToChar(self, S: str, C: str) -> List[int]: pos = [i for i in range(len(S)) if S[i]==C] return([min(abs(x-i) for i in pos) for x in range(len(S))])