LeetCode 题解工作台

判断国际象棋棋盘中一个格子的颜色

给你一个坐标 coordinates ,它是一个字符串,表示国际象棋棋盘中一个格子的坐标。下图是国际象棋棋盘示意图。 如果所给格子的颜色是白色,请你返回 true ,如果是黑色,请返回 false 。 给定坐标一定代表国际象棋棋盘上一个存在的格子。坐标第一个字符是字母,第二个字符是数字。 示例 1:…

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·string

bolt

答案摘要

观察棋盘我们发现,颜色相同的两个格子 $(x_1, y_1)$ 和 $(x_2, y_2)$ 满足 $x_1 + y_1$ 和 $x_2 + y_2$ 均为奇数或偶数。 因此,我们可以根据 获取对应的坐标 $(x, y)$,如果 $x + y$ 为奇数,则格子为白色,返回 ,否则返回 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个坐标 coordinates ,它是一个字符串,表示国际象棋棋盘中一个格子的坐标。下图是国际象棋棋盘示意图。

如果所给格子的颜色是白色,请你返回 true,如果是黑色,请返回 false 。

给定坐标一定代表国际象棋棋盘上一个存在的格子。坐标第一个字符是字母,第二个字符是数字。

 

示例 1:

输入:coordinates = "a1"
输出:false
解释:如上图棋盘所示,"a1" 坐标的格子是黑色的,所以返回 false 。

示例 2:

输入:coordinates = "h3"
输出:true
解释:如上图棋盘所示,"h3" 坐标的格子是白色的,所以返回 true 。

示例 3:

输入:coordinates = "c7"
输出:false

 

提示:

  • coordinates.length == 2
  • 'a' <= coordinates[0] <= 'h'
  • '1' <= coordinates[1] <= '8'
lightbulb

解题思路

方法一:找规律

观察棋盘我们发现,颜色相同的两个格子 (x1,y1)(x_1, y_1)(x2,y2)(x_2, y_2) 满足 x1+y1x_1 + y_1x2+y2x_2 + y_2 均为奇数或偶数。

因此,我们可以根据 coordinates\textit{coordinates} 获取对应的坐标 (x,y)(x, y),如果 x+yx + y 为奇数,则格子为白色,返回 true\textit{true},否则返回 false\textit{false}

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def squareIsWhite(self, coordinates: str) -> bool:
        return (ord(coordinates[0]) + ord(coordinates[1])) % 2 == 1
speed

复杂度分析

指标
时间complexity is O(1) because coordinate conversion and arithmetic are constant operations. Space complexity is O(1) as only a few integer variables are needed.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate understands converting characters to numeric indices for computation.

  • question_mark

    They identify that parity determines the chessboard color pattern.

  • question_mark

    They correctly handle the mapping of letters 'a' to 'h' to numerical values without off-by-one errors.

warning

常见陷阱

外企场景
  • error

    Misinterpreting the color mapping by reversing black and white parity.

  • error

    Off-by-one errors when converting letters to numbers ('a' vs 1).

  • error

    Ignoring that the sum of indices, not individual indices, determines the color.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Determine color for a rectangular chessboard of arbitrary size using the same parity approach.

  • arrow_right_alt

    Return the color as a string 'white' or 'black' instead of a boolean.

  • arrow_right_alt

    Given multiple coordinates, compute an array of boolean results for all squares efficiently.

help

常见问题

外企场景

判断国际象棋棋盘中一个格子的颜色题解:数学·string | LeetCode #1812 简单