LeetCode 题解工作台
检查棋盘方格颜色是否相同
给你两个字符串 coordinate1 和 coordinate2 ,代表 8 x 8 国际象棋棋盘上的两个方格的坐标。 以下是棋盘的参考图。 如果这两个方格颜色相同,返回 true ,否则返回 false 。 坐标总是表示有效的棋盘方格。坐标的格式总是先字母(表示列),再数字(表示行)。 示例 1…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·string
答案摘要
我们计算两个坐标的横纵坐标的差值,如果两个坐标的横纵坐标的差值之和为偶数,那么这两个坐标的方格颜色相同,否则不同。 时间复杂度 ,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路
题目描述
给你两个字符串 coordinate1 和 coordinate2,代表 8 x 8 国际象棋棋盘上的两个方格的坐标。
以下是棋盘的参考图。

如果这两个方格颜色相同,返回 true,否则返回 false。
坐标总是表示有效的棋盘方格。坐标的格式总是先字母(表示列),再数字(表示行)。
示例 1:
输入: coordinate1 = "a1", coordinate2 = "c3"
输出: true
解释:
两个方格均为黑色。
示例 2:
输入: coordinate1 = "a1", coordinate2 = "h3"
输出: false
解释:
方格 "a1" 是黑色,而 "h3" 是白色。
提示:
coordinate1.length == coordinate2.length == 2'a' <= coordinate1[0], coordinate2[0] <= 'h''1' <= coordinate1[1], coordinate2[1] <= '8'
解题思路
方法一:数学
我们计算两个坐标的横纵坐标的差值,如果两个坐标的横纵坐标的差值之和为偶数,那么这两个坐标的方格颜色相同,否则不同。
时间复杂度 ,空间复杂度 。
class Solution:
def checkTwoChessboards(self, coordinate1: str, coordinate2: str) -> bool:
x = ord(coordinate1[0]) - ord(coordinate2[0])
y = int(coordinate1[1]) - int(coordinate2[1])
return (x + y) % 2 == 0
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Checks if you understand mapping characters to numbers for arithmetic checks.
- question_mark
Tests ability to combine string parsing with modular arithmetic.
- question_mark
Observes if you optimize for O(1) rather than iterating the board.
常见陷阱
外企场景- error
Confusing row and column indices when converting letters to numbers.
- error
Forgetting to apply modulo 2, leading to incorrect color comparisons.
- error
Assuming a fixed board starting color without verifying the coordinate sums.
进阶变体
外企场景- arrow_right_alt
Determine if multiple pairs of squares all share the same color efficiently.
- arrow_right_alt
Check the color difference for a variable-sized chessboard using the same parity logic.
- arrow_right_alt
Return the color ('black' or 'white') instead of a boolean to generalize the solution.