下面记录一下这几天写的关于栈的简单题
思路:
将s遍历,如果是左括号就入栈,不是就进栈匹配,匹配成功就出栈,失败则直接返回False。
bool isValid(char * s){
int top = -1;
char Stack[strlen(s)];//创建栈
int i=0;
if(strlen(s)%2!=0)
return false;
while(1)
{
if(s[i]=='('||s[i]=='{'||s[i]=='[')//左括号入栈
{
if(s[i]=='(')
{
Stack[++top]=')';
}
else if(s[i]=='{')
{
Stack[++top]='}';
}
else
{
Stack[++top]=']';
}
}
else
{
if(top==-1&&i!=strlen(s)-1)//栈为空时匹配到右括号
return false;
else if(Stack[top]==s[i])//匹配成功,出栈
top--;
else//匹配失败
return false;
}
if(i==strlen(s)-1)
break;
i++;
}
if(top==-1)
return true;
else
return false;
}
注意:当栈为空时若匹配到右括号,不进行单独讨论的话,易造成数组越界。
思路:
将ops遍历,读取字符,按题目要求入栈。
int calPoints(char ** operations, int operationsSize){
int i;
int Stack[operationsSize];
int top=-1;
for(i=0;i<operationsSize;i++)
{
if(operations[i][0]=='C')
{
top--;
}
else if(operations[i][0]=='D')
{
Stack[++top]=Stack[top]*2;
}
else if(operations[i][0]=='+')
{
Stack[++top]=Stack[top-1]+Stack[top];
}
else
{
Stack[++top]=atoi(operations[i]);
}
}
int num=0;
for(i=0;i<=top;i++)
{
num+=Stack[i];
}
return num;
}
注意:
1、因为我们无法确定什么条件下是数字字符串,所以我们将其放在最后一个条件。
2、在编译器中,赋值等式是从右往左的所以进行运算的时候应注意数组越界问题。
else if(operations[i][0]=='D')
{
Stack[++top]=Stack[top]*2;
}
else if(operations[i][0]=='+')
{
Stack[++top]=Stack[top-1]+Stack[top];
}
在上面的代码中,不能写成:
else if(operations[i][0]=='D')
{
Stack[++top]=Stack[top-1]*2;
}
else if(operations[i][0]=='+')
{
Stack[++top]=Stack[top-1]+Stack[top-2];
}
因为不能误认为编译器是从左到右读取。