1. 程式人生 > 實用技巧 >LeetCode #246. Strobogrammatic Number

LeetCode #246. Strobogrammatic Number

題目

246. Strobogrammatic Number


解題方法

能夠滿足條件的數只有0、1、6、8、9幾個,且只有0、1、8可以自我180°對稱,6和9必須要配對出現。所以做一個字典dic把這些數加進去,然後根據陣列長度是否是奇數來看看是不是要判斷一下中間那個數是否在0、1、8幾個裡面。這樣之後就可以把字串num從中間劈開,分別設定left和right指標從中間向兩邊遍歷,判斷對應位置是否配對即可。
時間複雜度:O(n)
空間複雜度:O(1)


程式碼

class Solution:
    def isStrobogrammatic(self, num: str) -> bool:
        dic = {
            "0":"0",
            "1":"1",
            "6":"9",
            "8":"8",
            "9":"6"
        }
        
        n = len(num)
        left =  n // 2 - 1
        right = n // 2
        if n % 2:
            if num[right] not in {"0", "1", "8"}: return False
            right += 1
        
        while left > -1:
            if num[left] not in dic or num[right] not in dic:
                return False
            if dic[num[left]] != num[right] or dic[num[right]] != num[left]:
                return False
            left -= 1
            right += 1
        
        return True