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

LeetCode 171: Excel Sheet Column Number

·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-21

  • 提交紀錄:Runtime Error → Accepted ×7

解題思路
#

LC 168 的反方向(Math 模板七):每一位的值是 ord(c) - ord("A") + 1,從左到右 res = res * 26 + 值,跟把十進位字串轉成整數一樣。

我的嘗試
#

第一版寫成 for i, n in columnTitle[::-1],少了 enumerate,拆不出兩個值(ValueError)。補上就 AC 了。

正確解法
#

class Solution:
    def titleToNumber(self, columnTitle: str) -> int:
        res = 0
        for c in columnTitle:
            res = res * 26 + ord(c) - ord("A") + 1
        return res

複雜度
#

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

要特別避免的錯誤
#

  • A 是 1,不是 0。
  • 要同時拿 index 和字元時用 enumerate。

面試口說整理
#

我從左到右掃,每次把目前的結果乘 26 再加上這個字母的值,A 是 1。時間 O(n)。

相關文章

LeetCode 168: Excel Sheet Column Title
·1 分鐘
LeetCode Easy Math String
LeetCode 168 解題筆記:Excel 欄名是沒有 0 的 26 進位,每一位用 (n - 1) % 26 取字母,再 n = (n - 1) // 26
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 202: Happy Number
·1 分鐘
LeetCode Easy Hash-Table Math Two-Pointers Floyds-Cycle-Finding-Algorithm
LeetCode 202 解題筆記:一直取位數平方和,會走到 1 或進入環;用集合記看過的數,或用快慢指針判圈
LeetCode 205: Isomorphic Strings
·1 分鐘
LeetCode Easy Hash-Table String
LeetCode 205 解題筆記:兩個字串的字元要一對一對應,字元種類數和配對種類數都相同就成立
LeetCode 125: Valid Palindrome
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 125 解題筆記:左右指針跳過非英數字元,再比較小寫是否相同;數字也要算進去