LeetCode20. Valid Parentheses
题目:
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.
题目分析:
很简单的一道题,在大二的时候就已经做过了很多次了,就是简单的括号匹配,用栈去模拟。
代码:
#include<iostream>]
#include<stack>
#include<string>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> stack;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '{' || s[i] == '[' || s[i] == '(') {
stack.push(s[i]);
}
else if (s[i] == '}' || s[i] == ']' || s[i] == ')') {
if (stack.empty()) {
return false;
}
else {
if (stack.top() != pipei(s[i])) {
return false;
}
else {
stack.pop();
}
}
}
}
if (!stack.empty()) {
return false;
}
return true;
}
char pipei(char a) {
if (a == '}') {
return '{';
}
else if (a == ']') {
return '[';
}
else if (a == ')') {
return '(';
}
return ' ';
}
};