problem
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.
answer
class Solution {
public:
bool isValid(string s) {
stack<char> pStack;
int i = 0;
// if(s.size() == 1){
// return false;
// }
while(s[i] != '\0'){
// if(pStack.empty() && (s[i]==')') || s[i]==']' || s[i]=='}'){
// return false;
// }
if(s[i] == '(' || s[i] == '[' || s[i] == '{'){
pStack.push(s[i++]);
}
else if(!pStack.empty() && ((s[i] == ')' && pStack.top() == '(') || (s[i] == ']' && pStack.top() == '[') || (s[i] == '}' && pStack.top() == '{'))){
pStack.pop();
i++;
}
else{
return false;
}
}
if(!pStack.empty()){
return false;
}
return true;
}
};
time:0ms