我用C++写的,下面是通过的代码。
从昨天开始调试的,今天早上刚找到原因,已经提交了,过程中间一直有问题。
我想记录下来的是stack的用法:
stack后面一定要写<char>,不然会报错
其中长度的话是size()而不是length().
pop()表示弹出
push(item)表示压入
top()表示最顶层的元素
一直有问题的地方是在下面加//*的地方。之前直接用c和top()比,然后就一直得到false,无论如何true都得不到。后来发现是这里写错了。脑子没转过来,最近该补脑了……
#include <stack>
#include <iostream>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> st;
char c;
int i;
for(i=0;i<s.size();i++)
{
c=s[i];
if((c=='(')||(c=='{')||(c=='['))
{
st.push(c);
}
else if((c==')')||(c=='}')||(c==']'))//*
{
if(!st.empty())
{
if(st.top()=='(')
{
if(c==')'){st.pop();}
else{return false;}
}
else if(st.top()=='{')
{
if(c=='}'){st.pop();}
else{return false;}
}
else if(st.top()=='[')
{
if(c==']'){st.pop();}
else{return false;}
}
}
else{return false;}
}
}
if(!st.empty())
{return false;}
else{return true;}
// return st.empty();
}
};