85ms
class Solution(object):
def shortestToChar(self, S, C):
"""
:type S: str
:type C: str
:rtype: List[int]
"""
result = [S.find(C)]
for i in xrange(1,len(S)):
left = 1e5
right = 1e5
if C in S[:i]:
left = S[i-1::-1].find(C) + 1
if C in S[i:]:
right = S[i:].find(C)
result.append(min(left,right))
return result
----------------------------
上一个位置结果对当前计算有用
76ms
class Solution(object):
def shortestToChar(self, S, C):
"""
:type S: str
:type C: str
:rtype: List[int]
"""
find = 0
position = S.find(C)
result = [position]
for i in xrange(1,len(S)):
sub = position - i
if sub>=0:
result.append(sub)
else:
find = S[i:].find(C)
if find<-sub and find>-1:
position = i+find
result.append(find)
else:
result.append(-sub)
return result
-------------------------------------
note:正无穷的赋值方法 pre = float('inf') 负无穷的赋值方法:pre = float('-inf')
遍历两遍,第一遍记录每个位置的左边最近的位置,第二遍记录每个位置的右边最近的位置
64ms
class Solution(object):
def shortestToChar(self, S, C):
"""
:type S: str
:type C: str
:rtype: List[int]
"""
result = []
pre = -1e5
left = []
for i,item in enumerate(S):
if item==C:
pre = i
left.append(i-pre)
pre = 1e5
for i in xrange(len(S)-1,-1,-1):
if S[i]==C:
pre = i
left[i] = (min(left[i],pre-i))
return left