Leetcode题库 2038.邻色同删(双指针法 C实现)

文章目录

解析

temp数组:
用于记录字符串colors中字符的状态
二维数组p:
存放两个指针*p, *(p+1)分别存放两选手当前在字符串中搜索的起始位置

代码

//colors 字符串
//temp 字符删除情况
//l 字符串长度
//c 需搜索字符
//p 搜索起始位置
//搜索成功返回index, 否则返回-1
int Find(char *colors,int *temp,int l,char c,int *p){
    int ret=-1, t, left, right;
    //ret 返回值
    //t 左右相邻下标
    //left 1左邻c; 0左邻非c
    //righ 1右邻c; 0右邻非c
    for(int i=*p;i<l;i++){//搜寻
        left=0;
        right=0;
        if(temp[i]==1 && colors[i]==c){//若i位置字符未被删除并且为c
            t=i;
            for(int j=i-1;j>=0;j--){//左1搜索
                if(temp[j]==1){
                    t=j;
                    break;
                }
            }
            if(t!=i && colors[t]==c) left=1;

            t=i;
            for(int j=i+1;j<l;j++){//右1搜索
                if(temp[j]==1){
                    t=j;
                    break;
                }
            }
            if(t!=i && colors[t]==c) right=1;
        }
        if(left==1 && right==1){
            ret=i;
            break;
        }
    }
    return ret;
}

bool winnerOfGame(char * colors){
    int l=strlen(colors);
    if(l<3) return false;
    int *temp=(int*)malloc(sizeof(int)*l);
    for(int i=0;i<l;i++){*(temp+i)=1;}
    //l 字符串长度
    //temp 记录字符删除情况

    char str[2]={'A','B'};
    int turn=0, flag=-1, Index;
    int p[2][1];
    **p=0;
    **(p+1)=0;
    //str AB数组
    //turn 0:Alice轮次; 1:Bob轮次
    //flag 0:Alice胜; 1:Bob胜
    //接收Find搜寻位置
    //p0 指向Alice已经搜索到的位置
    //p1 指向Bob已经搜索到的位置
    while(1){
        Index=Find(colors, temp, l, str[turn], *(p+turn));
        if(Index!=-1){
            **(p+turn)=Index+1;
            turn=1-turn;
        }else{
            flag=1-turn;
            break;
        }  
    }
    return flag==0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值