LeetCode 🟢 3931. Check Adjacent Digit Differences
🔗 🟢 3931. Check Adjacent Digit Differences
Problem Statement
題目簡述
給定一個僅由數字組成的字串 。
若每一對相鄰數字之間的絕對差值皆不超過 (即對所有相鄰的 滿足 ),則回傳 true;否則回傳 false。
Constraints
約束條件
- 僅由數字字元
'0'–'9'組成
思路:模擬
直接依題意線性掃描每一對相鄰數字即可。將字串中的每個字元轉為整數後,使用 pairwise 逐一配對相鄰元素,並以 all 驗證所有相鄰數字對是否皆滿足 ;只要遇到任一對差值大於 便會提前短路回傳 False。
複雜度分析
- 時間複雜度:,其中 為字串 的長度,線性遍歷所有相鄰數字對一次。
- 空間複雜度:,
map與pairwise皆為惰性迭代器,不需額外配置陣列空間。
Code
1 | class Solution: |
寫在最後
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.
本部落格所有文章除特別聲明外,均採用CC BY-NC-SA 4.0 授權協議。轉載請註明來源 十六個天亮!
評論
WalineGiscus






