解析
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;
}