对比笔记(数组栈和stl中stack)
1:我写的数组栈,在“有效括号中”是如何工作的。
什么时候push?
在将已知输入数据压入栈中时,且为左括号类型。
什么时候pop?
在确定碰见的右括号类型与栈顶元素匹配时。为了不妨碍下一个碰见的右括号与另一个去除原先栈顶元素的栈顶元素比较。
栈空/不空分别代表什么?
栈空代表所有左括号类型有相应的右括号类型。不空代表有不匹配的左右符号(按顺序)。
2:如果用stl的stack
那部分变简单了?
不用自创一个栈和相应对栈操作的函数,直接可以调用相关函数
底层思想是否一样?
底层思想一样,都是通过栈的特性进行判断匹配。
3:这个题为什么不能用队列?
因为两者特性决定,栈为后进先出,队列为先进先出,后进先出便于题中的顺序匹配,如(【】)。
class Mystack{
private:
char *data;
int capacity;
int topIndex;
public:
Mystack(int cap)
{
capacity=cap;
topIndex=-1;
data=new char[cap];
}
~Mystack()
{
delete[] data;
}
void push(char s)
{
if((topIndex+1)==capacity)
{
return ;
}
data[++topIndex]=s;
}
char pop()
{
if(topIndex==-1)
{
return -1;
}
return data[topIndex--];
}
char top()
{
if(!Isempty())
{
return data[topIndex];
}
else {return -1;}
}
bool Isempty()
{
return topIndex==-1;
}
bool Isfull()
{
return (topIndex+1)==capacity;
}
};
class Solution {
public:
bool isValid(string s) {
int n=s.size();
if(n==1)
{
return 0;
}
if(n==0)
{
return 1;
}
Mystack a(n);
for(int i=0;i<n;i++)
{
if(!a.Isfull())
{
if(s[i]=='(' ||s[i]=='['||s[i]=='{')
{
a.push(s[i]);
}
if(s[i]==')' ||s[i]==']'||s[i]=='}')
{
if(a.Isempty())
{
return 0;
}
char topchar=a.top();
if((s[i]==')' && topchar!='(')||(s[i]==']' && topchar!='[')||(s[i]=='}' && topchar!='{'))
{return 0;}
else {a.pop();}
}
}
}
if(a.Isempty())
{
return 1;
}
return 0;
}
};
这道题核心是括号匹配顺序和栈的后进先出一致。
遇见左括号入栈,右括号检查栈顶是否匹配。
如果中途不匹配,或最后栈不空就无效。
我特意用自己的数组栈实现,证明我理解栈的底层。

浙公网安备 33010602011771号