↓快轉到主要內容
  1. LeetCode/

LeetCode 168: Excel Sheet Column Title

·1 分鐘· ·
LeetCode Easy Math String
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-08-20

  • 提交紀錄:Internal Error → Wrong Answer ×3 → Runtime Error ×3 → Wrong Answer → Accepted

解題思路
#

一般的進位制每一位是 0..25,但欄名每一位是 1..26(A..Z),沒有 0。所以每一步先 n -= 1,把 1..26 平移成 0..25,再用 % 26 取最後一位的字母、// 26 往前(Math 模板七)。最後把字母反轉。

我的嘗試
#

這題提交了 9 次:

  • 前四版假設最多兩個字母,寫成 capitals[n // 26] + capitals[n % 26]:1 回傳 "AB",答案 "A"。
  • 改成遞迴之後,一版參數名稱打錯(NameError),一版只有字母那邊減 1,遞迴往前的那邊沒有減:52 回傳 "BZ",答案 "AZ"。兩邊都用 n - 1 才 AC。

正確解法
#

class Solution:
    def convertToTitle(self, columnNumber: int) -> str:
        res = []
        n = columnNumber
        while n:
            n, r = divmod(n - 1, 26)
            res.append(chr(ord("A") + r))
        return "".join(reversed(res))

複雜度
#

時間 O(log n),空間 O(log n)。

要特別避免的錯誤
#

  • 每一步都要先減 1,不是只有最後一位:52 是 "AZ",不是 "BZ"。
  • 位數不固定,不能假設最多兩個字母。

面試口說整理
#

欄名是沒有 0 的 26 進位,每一位是 1 到 26,所以我每一步先減一變成 0 到 25,取餘數當字母、整除後繼續,最後反轉。時間 O(log n)。

相關文章

LeetCode 67: Add Binary
·1 分鐘
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 解題筆記:從兩個字串的尾巴往前逐位相加,進位是 sum // 2,這一位是 sum % 2
LeetCode 13: Roman to Integer
·1 分鐘
LeetCode Easy Hash-Table Math String
LeetCode 13 解題筆記:從左到右加每個符號的值,如果它比右邊的符號小就改成減
LeetCode 125: Valid Palindrome
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 125 解題筆記:左右指針跳過非英數字元,再比較小寫是否相同;數字也要算進去
LeetCode 69: Sqrt(x)
·1 分鐘
LeetCode Easy Math Binary-Search Newtons-Method
LeetCode 69 解題筆記:找最大的 mid 讓 mid² <= x;閉區間二分結束時 r 就是答案
LeetCode 28: Find the Index of the First Occurrence in a String
·1 分鐘
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 解題筆記:在每個起點比對 needle,或直接用 str.find;index 找不到會丟例外
LeetCode 58: Length of Last Word
·1 分鐘
LeetCode Easy String
LeetCode 58 解題筆記:split() 不帶參數會忽略結尾的空白,取最後一個單字的長度