leetcode 1812. Determine Color of a Chessboard Square(python)

266 阅读1分钟

描述

You are given coordinates, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.

avatar

Return true if the square is white, and false if the square is black.

The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.

Example 1:

Input: coordinates = "a1"
Output: false
Explanation: From the chessboard above, the square with coordinates "a1" is black, so return false.	

Example 2:

Input: coordinates = "h3"
Output: true
Explanation: From the chessboard above, the square with coordinates "h3" is white, so return true.

Example 3:

Input: coordinates = "c7"
Output: false

Note:

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

解析

根据题意,就是判断图中对应坐标的格子是不是白色的。思路很简单,不在赘述,更偷懒的方法就是将所有表格的颜色存在一个字典里,直接进行判断速度更快,但是有点麻烦。哈哈。

解答

class Solution(object):
    def squareIsWhite(self, coordinates):
        """
        :type coordinates: str
        :rtype: bool
        """
        x = coordinates[0]
        y = coordinates[1]
        if ((ord(x)-ord('a')+1)+int(y)) % 2 != 0:
            return True
        return False
        	      
		

运行结果

Runtime: 20 ms, faster than 38.87% of Python online submissions for Determine Color of a Chessboard Square.
Memory Usage: 13.5 MB, less than 45.97% of Python online submissions for Determine Color of a Chessboard Square.

原题链接:leetcode.com/problems/de…

您的支持是我最大的动力