🔗 🟢 3931. Check Adjacent Digit Differences

Problem Statement

題目簡述

給定一個僅由數字組成的字串 ss。
若每一對相鄰數字之間的絕對差值皆不超過 22(即對所有相鄰的 a,ba, b 滿足 ∣a−b∣≤2|a - b| \le 2),則回傳 true;否則回傳 false。

Constraints

約束條件

  • 2≤s.length≤1002 \le s.\text{length} \le 100
  • ss 僅由數字字元 '0'–'9' 組成

思路:模擬

直接依題意線性掃描每一對相鄰數字即可。將字串中的每個字元轉為整數後,使用 pairwise 逐一配對相鄰元素,並以 all 驗證所有相鄰數字對是否皆滿足 ∣a−b∣≤2|a - b| \le 2;只要遇到任一對差值大於 22 便會提前短路回傳 False。

複雜度分析

  • 時間複雜度:O(n)\mathcal{O}(n),其中 nn 為字串 ss 的長度,線性遍歷所有相鄰數字對一次。
  • 空間複雜度:O(1)\mathcal{O}(1),map 與 pairwise 皆為惰性迭代器,不需額外配置陣列空間。

Code

1
2
3
class Solution:
def isAdjacentDiffAtMostTwo(self, s: str) -> bool:
return all(abs(a - b) <= 2 for a, b in pairwise(map(int, s)))

寫在最後

Cover Image Credit

The cover image features an artwork created by @⚠️AI-Generated. All rights belong to the original artist.

If you are the copyright holder and prefer it not to be used here, please reach out via email or leave a comment, and I will remove it promptly.