美文网首页
8.24 - hard - 103

8.24 - hard - 103

作者: 健时总向乱中忙 | 来源:发表于2017-08-25 08:55 被阅读0次

564. Find the Closest Palindrome
一道数学题。。。重点是找到各种情况并且对其简化。分成两种情况,第一种是如果S[:half] 的最后一个值 +(-1,0,1)然后翻转,第二种情况是如果要找的值和S不一样长,那么肯定是 "9...9"和“10..01”之间的一个

class Solution(object):
    def nearestPalindromic(self, n):
        """
        :type n: str
        :rtype: str
        """
        S = n
        K = len(S)
        candidates = [str(10**k + d) for k in (K-1, K) for d in (-1, 1)]
        prefix = S[:(K+1)/2]
        P = int(prefix)
        for start in map(str, (P-1, P, P+1)):
            candidates.append(start + (start[:-1] if K%2 else start)[::-1])

        def delta(x):
            return abs(int(S) - int(x))

        ans = None
        for cand in candidates:
            if cand != S and not cand.startswith('00'):
                if (ans is None or delta(cand) < delta(ans) or
                        delta(cand) == delta(ans) and int(cand) < int(ans)):
                    ans = cand
        return ans

相关文章

  • 8.24 - hard - 103

    564. Find the Closest Palindrome一道数学题。。。重点是找到各种情况并且对其简化。分...

  • 8.24 - hard - 104

    568. Maximum Vacation Days 又是一道dp,感觉用心去想还是可以做出来的,不过有点做不动了...

  • 8.24 - hard - 105

    587. Erect the Fence 利用一种算法叫做Monotone Chain,加上之前的旋转卡壳。。。还...

  • 8.24 - hard - 101

    546. Remove Boxes 先做出来一个backtracking的TLE版本,下面想想如何加memory,...

  • 8.24 - hard - 102

    552. Student Attendance Record II虽然知道这是一道DP题,但是这个dp状态真的很难...

  • 同舟人,誓相随,无畏更无惧

    8.24

  • 跑步第32天(37)

    8.24 休息

  • 2018-06-29

    8.24第一轮

  • 19/09/2017

    Work hard,play hard,study hard, love hard.一个小姐姐跟我这么说。她说后两...

  • 2019.8.24

    8.24 【阅读】8.24朗读《花钟》没有生字,可以有感情的读!8.23朗读《小鸡的家》三个生字, 【拼音】8.2...

网友评论

      本文标题:8.24 - hard - 103

      本文链接:https://www.haomeiwen.com/subject/mxaydxtx.html