LeetCode 5448. 判断路径是否相交(set)

1. 题目

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

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

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

示例 1:
在这里插入图片描述

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

示例 2:
在这里插入图片描述

输入:path = "NESWW"
输出:true
解释:该路径经过原点两次。
 
提示:
1 <= path.length <= 10^4
path 仅由 {'N', 'S', 'E', 'W} 中的字符组成

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/path-crossing
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • set 查重即可
class Solution {//C++
public:
    bool isPathCrossing(string path) {
        set<pair<int,int>> s;
        s.insert({0,0});
        int x = 0, y = 0;
        for(int i = 0; i < path.size(); i++)
        {
            if(path[i] == 'N')
                y++;
            else if(path[i] == 'S')
                y--;
            else if(path[i] == 'E')
                x++;
            else
                x--;
            if(s.find({x,y}) != s.end())
                return true;
            else
                s.insert({x,y});
        }
        return false;
    }   
};

4 ms 6.9 MB

class Solution:#py3
    def isPathCrossing(self, path: str) -> bool:
        s = set()
        s.add(tuple([0,0]))
        x = 0
        y = 0
        for i in range(len(path)):
            if path[i] == 'N':
                y += 1
            elif path[i] == 'S':
                y -= 1
            elif path[i] == 'E':
                x += 1
            else:
                x -= 1
            if tuple([x,y]) in s:
                return True;
            else:
                s.add(tuple([x,y]))
        return False

44 ms 13.7 MB

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/106996303