题目描述
你现在是一场采特殊赛制棒球比赛的记录员。这场比赛由若干回合组成,过去几回合的得分可能会影响以后几回合的得分。
比赛开始时,记录是空白的。你会得到一个记录操作的字符串列表 ops,其中 ops[i] 是你需要记录的第 i 项操作,ops 遵循下述规则:
- 整数 x - 表示本回合新获得分数 x
- “+” - 表示本回合新获得的得分是前两次得分的总和。题目数据保证记录此操作时前面总是存在两个有效的分数。
- “D” - 表示本回合新获得的得分是前一次得分的两倍。题目数据保证记录此操作时前面总是存在一个有效的分数。
- “C” -表示前一次得分无效,将其从记录中移除。题目数据保证记录此操作时前面总是存在一个有效的分数。
请你返回记录中所有得分的总和。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/baseball-game
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
- 题解1
使用if判断语句,时间较长
int calPoints(char ** ops, int opsSize){
int score[1000];
int top=-1;
int sum=0;
for(int i=0;i<opsSize;i++)
{
if(ops[i][0]=='C')
{
top--;
}
else if(ops[i][0]=='D')
{
top++;
score[top]=score[top-1]*2;
}
else if(ops[i][0]=='+')
{
top++;
score[top]=score[top-1]+score[top-2];
}
else
{
top++;
score[top]=0;
if(ops[i][0]=='-')
{
for(int j=1;ops[i][j]!='\0';j++)
{
score[top]*=10;
score[top]-=(int)ops[i][j]-48;
}
}
else
{
for(int j=0;ops[i][j]!='\0';j++)
{
score[top]*=10;
score[top]+=(int)ops[i][j]-48;
}
}
}
}
for(int i=0;i<=top;i++)
{
sum+=score[i];
}
return sum;
}
- 改进
使用switch,时间缩短
int calPoints(char ** ops, int opsSize){
int score[1000];
int top=-1;
int sum=0;
for(int i=0;i<opsSize;i++)
{
switch (ops[i][0])
{
case 'C':
top--;
break;
case 'D':
top++;
score[top]=score[top-1]*2;
break;
case '+':
top++;
score[top]=score[top-1]+score[top-2];
break;
default:
top++;
score[top]=0;
if(ops[i][0]=='-')
{
for(int j=1;ops[i][j]!='\0';j++)
{
score[top]*=10;
score[top]-=(int)ops[i][j]-48;
}
}
else
{
for(int j=0;ops[i][j]!='\0';j++)
{
score[top]*=10;
score[top]+=(int)ops[i][j]-48;
}
}
break;
}
}
for(int i=0;i<=top;i++)
{
sum+=score[i];
}
return sum;
}
- 改进2
- 使用C语言库函数atoi,将字符串整数转成整形整数,使用空间稍微增加
- 根据字符串长度使用malloc函数分配内存
int calPoints(char ** ops, int opsSize){
int* score=(int *)malloc(opsSize*sizeof(int));
int top=-1;
int sum=0;
for(int i=0;i<opsSize;i++)
{
switch (ops[i][0])
{
case 'C':
top--;
break;
case 'D':
top++;
score[top]=score[top-1]*2;
break;
case '+':
top++;
score[top]=score[top-1]+score[top-2];
break;
default:
top++;
score[top]=atoi(ops[i]);
break;
}
}
for(int i=0;i<=top;i++)
{
sum+=score[i];
}
return sum;
}