原题:
Given a string containing just the characters '('
, ')'
,'{'
,'}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but"(]"
and"([)]"
are not.
首先string长度必须为偶数,否则报错。其次每一对括号必须在一起,否则报错。
代码:
class Solution {
public:
bool isValid(string s) {
if (s.size()%2!=0) return false;
for (int j = 0; j<s.size()-1; j+=2){
if(s[j]=='(') {
if(s[j+1]==')') continue;
else return false;
}
if(s[j]=='[') {
if(s[j+1]==']') continue;
else return false;
}
if(s[j]=='{') {
if(s[j+1]=='}') continue;
else return false;
}
}
}
};
报错了…
=================================================================================================================================
之前读题有问题,后来再理解一遍后觉得,还是需要一个堆栈的。重写代码如下:
class Solution {
public:
bool isValid(string s) {
stack<char> p;
char c;
for(int i = 0; i<s.size(); i++){
if(s[i]=='(' || s[i]=='[' || s[i]=='{') p.push(s[i]);
else{
if(p.empty()) return false;
c = p.top();
if((s[i]==')' && c=='(')||(s[i]==']' && c=='[')||(s[i]=='}' && c=='{')) p.pop();
else return false;
}
}
if (!p.empty()) return false;
return true;
}
};
但还是卡在一样的地方了,WA…
================================================================================================================================
class Solution {
public:
bool isValid(string s) {
stack<char> p;
for(int i = 0; i<s.size(); i++){
if(s[i]=='(' || s[i]=='[' || s[i]=='{') p.push(s[i]);
else{
if(p.empty()) return false;
if((s[i]==')' && p.top()=='(')||(s[i]==']' && p.top()=='[')||(s[i]=='}' && p.top()=='{')) p.pop();
else return false;
}
}
if (!p.empty()) return false;
return true;
}
};
AC了。
你真得没有在逗我么- -#