3484. Design Spreadsheet | LeetCode | Swift

vc7-avatar-img
發佈於LeetCode
更新 發佈閱讀 3 分鐘

每日一題

日期

2025/9/19

資料結構

為了快速存取資料,這一題可以利用 HashMap 解。A1 就直接作為 key 值,不需要拆開英文和數字和不用建立二維的資料結構。

解開 formula

這題的核心演算法就在 getValue 這個方法 。我在這邊用了兩次分割字串,根據 =+ 分離出兩個要運算的數值。

解析數值

根據題意,有兩個情境

  1. 英文加數字:從 HashMap 試著取用,失敗的話回傳 0
  2. 純數字:試著轉換成 Int ,失敗的話使用 0

合併起來如下

private func value(_ key: String) -> Int {
hashTable[key] ?? Int(key) ?? 0
}

程式碼

class Spreadsheet {

private var values = [String: Int]()

init(_ rows: Int) {}

func setCell(_ cell: String, _ value: Int) {
values[cell] = value
}

func resetCell(_ cell: String) {
values[cell] = 0
}

func getValue(_ formula: String) -> Int {
formula
.components(separatedBy: "=")[1]
.components(separatedBy: "+")
.map(value)
.reduce(0, +)
}

private func value(_ key: String) -> Int {
values[key] ?? Int(key) ?? 0
}
}
留言
avatar-img
留言分享你的想法!
avatar-img
萱寫寫
3會員
19內容數
讀書心得、活動參加心得
萱寫寫的其他內容
2025/09/18
LeetCode 每日一題: 2025/09/18
2025/09/18
LeetCode 每日一題: 2025/09/18
2025/09/17
LeetCode 每日一題: 2025/09/17
2025/09/17
LeetCode 每日一題: 2025/09/17
2025/09/16
2025/09/16
看更多