#include<stack>
class Solution {
public:
bool isValid(string s) {
stack<char> str;
char top='0';
for(int i=0;i<s.size();i++){
str.push(s[i]);
if(s[i]==')'&&top=='('){
str.pop();
str.pop();
}
else if(s[i]==']'&&top=='['){
str.pop();
str.pop();
}
else if(s[i]=='}'&&top=='{'){
str.pop();
str.pop();
}
if(!str.empty())
top=str.top();
}
if(str.empty())
return true;
else
return false;
}
};
利用栈后进先出…主要半学期没接触数据结构没写过c艹代码这次突然做对栈和字符串的相关用法不熟悉了。注意非空的时候才能取top,否则内存越界