使用栈,先将左括号入栈,然后遍历字符串,在对括号进行匹配
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串 s
,判断字符串是否有效。
//有效的括号 #include<iostream> #include<stack> #include<string> #include<vector> using namespace std; class Solution { public: bool isValid(string s); }; bool Solution::isValid(string s) { vector<char> left; char right; int n = s.length(); int left_count = 0; if (n % 2 == 0 && s[0] != '}' && s[0] != ']' && s[0] != ')'){ for (int i = 0; i < n; i++) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') { left.push_back(s[i]); } else { right = s[i]; int num = left.size(); char temp = left.at(num - 1); if (right == ')' && temp == '(') { left.pop_back(); } else if (right == '}' && temp == '{') { left.pop_back(); } else if (right == ']' && temp == '[') { left.pop_back(); } else return 0; } } int count = left.size(); if (count == 0) return 1; else { return 0; } } else { return 0; } } int main() { string s; cin >> s; Solution so; cout << so.isValid(s) << endl; return 0; }