数据结构和算法分析LeetCode solutions算法提高之LeetCode刷题

LeetCode 5448. 判断路径是否相交(195周赛)

2020-06-28  本文已影响0人  freesan44

题目

给你一个字符串 path,其中 path[i] 的值可以是 'N''S''E' 或者 'W',分别表示向北、向南、向东、向西移动一个单位。

机器人从二维平面上的原点 (0, 0) 处开始出发,按 path 所指示的路径行走。

如果路径在任何位置上出现相交的情况,也就是走到之前已经走过的位置,请返回 True ;否则,返回 False

示例 1:


输入:path = "NES"
输出:false
解释:该路径没有在任何位置相交。</pre>

示例 2:

image

输入:path = "NESWW"
输出:true
解释:该路径经过原点两次。</pre>

提示:

解题思路

用数组记录曾经走过的路径

    def isPathCrossing(self, path: str) -> bool:
        pathList = list(path)
        stepList = ["0 0"]
        while len(pathList)>0:
            # print(stepList)
            step = pathList.pop(0)
            lastStep = stepList[-1]
            tempList = lastStep.split(" ")
            x = int(tempList[0])
            y = int(tempList[1])
            if step == "N":
                y = y +1
            elif step == "S":
                y = y - 1
            elif step == "E":
                x = x + 1
            elif step == "W":
                x = x - 1
            newStepStr = str(x) + " " + str(y)
            if newStepStr in stepList:
                return True
            stepList.append(newStepStr)
        return False
上一篇下一篇

猜你喜欢

热点阅读