1496. 判断路径是否相交-哈希表法

1496. 判断路径是否相交-哈希表法

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

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

如果路径在任何位置上与自身相交,也就是走到之前已经走过的位置,请返回 true ;否则,返回 false 。

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

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

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

输入:path = “NESWW”
输出:true
解释:该路径经过原点两次。

这题用哈希表去做是很不错的,解题代码如下:

#define size 10000
struct hash{
    struct hash *next;
    int x;
    int y;
};
void add_hash(struct hash* h,int x,int y){
    struct hash*p=(struct hash *)malloc(sizeof(struct hash ));
    p->x=x;
    p->y=y;
    p->next=h->next;
    h->next=p;

}

bool find_hash(struct hash *h,int x,int y){
    struct hash*p=h->next;
   
    while(p){
        
        if(p->y==y&&p->x==x){
         return true;
           
        }
        p=p->next;
    }
    return false;
}

bool isPathCrossing(char * path){
    struct hash *h=(struct hash *)malloc(sizeof(struct hash )*size);
    for(int i=0;i<size;i++){
        (h+i)->next=NULL;
    }
    int x=0,y=0;
    add_hash(h+0%size,0,0);

    for(int i=0;path[i]!='\0';i++){
        char ch=path[i];
        if(ch=='N'){
            y=y+1;

        }
        else if(ch=='S'){
            y=y-1;

        }
         else if(ch=='E'){
            x=x+1;

        } 
        else if(ch=='W'){
            x=x-1;

        }
       // printf("%d %d ",x,y);
        if(find_hash(h+abs(x)%size,x,y)){
            return true;
        }
         add_hash(h+abs(x)%size,x,y);



       
    }
    return false;
    


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值