【leetcode】821. Shortest Distance to a Character

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值