946.验证栈序列
题目
题解
typedef struct Stack{
int* data;
int ptr;
}Stack;
bool validateStackSequences(int* pushed, int pushedSize, int* popped, int poppedSize){
//栈初始化
Stack s;
s.data = (int*)malloc(sizeof(int)*pushedSize);
s.ptr = -1;
//不断进栈,每次进栈后不断匹配,如果匹配上了就出栈
int pushPtr = 0;
int popPtr = 0;
while(pushPtr < pushedSize){
s.data[++s.ptr] = pushed[pushPtr++];
while(s.ptr!=-1 && s.data[s.ptr] == popped[popPtr]){
s.ptr--;
popPtr++;
}
}
if(s.ptr == -1){
return true;
}
return false;
}
要点
在匹配时要检测栈的指针是否已经等于-1了,防止栈溢出。
1275.找出井字棋的获胜者
题目
题解
char * tictactoe(int** moves, int movesSize, int* movesColSize){
int AH[3]={0},AL[3]={0},AX[2]={0};
int BH[3]={0},BL[3]={0},BX[2]={0};
int i = 0;
for(;i < movesSize;i++){
if(i%2 == 0){//A
//行
AH[moves[i][0]]+=1;
if(AH[moves[i][0]] == 3){
char* s = "A";
return s;
}
//列
AL[moves[i][1]]+=1;
if(AL[moves[i][1]] == 3){
char* s = "A";
return s;
}
//斜对角线
if(moves[i][0]==moves[i][1]){
AX[0] += 1;
if(AX[0] == 3){
char* s = "A";
return s;
}
}
//副对角线
if((moves[i][0]==0&&moves[i][1]==2)||(moves[i][0]==1&&moves[i][1]==1)||(moves[i][0]==2&&moves[i][1]==0)){
AX[1] += 1;
if(AX[1] == 3){
char* s = "A";
return s;
}
}
}else{//B
//行
BH[moves[i][0]]+=1;
if(BH[moves[i][0]] == 3){
char* s = "B";
return s;
}
//列
BL[moves[i][1]]+=1;
if(BL[moves[i][1]] == 3){
char* s = "B";
return s;
}
//斜对角线
if(moves[i][0]==moves[i][1]){
BX[0] += 1;
if(BX[0] == 3){
char* s = "B";
return s;
}
}
//副对角线
if((moves[i][0]==0&&moves[i][1]==2)||(moves[i][0]==1&&moves[i][1]==1)||(moves[i][0]==2&&moves[i][1]==0)){
BX[1] += 1;
if(BX[1] == 3){
char* s = "B";
return s;
}
}
}
}
if(movesSize == 9){
char* s = "Draw";
return s;
}
char* s = "Pending";
return s;
}
要点
预设A、B的行、列、对角线得分,当满足时即获胜。
c语言字符串指针的赋值:char *s = "hello";