青岛工商代理公司注册谷歌seo外包
- 有效的括号
https://leetcode.cn/problems/valid-parentheses/description/
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
class Solution {
public:vector<char> left = {'(', '[', '{'};vector<char> right = {')', ']', '}'}; //这样写可以便于拓展更多的其他符号bool isValid(string s) {stack<char> st;for (int i = 0; i < s.size(); i++) {for (int j = 0; j < left.size(); j++) {if (s[i] == left[j]) {st.push(left[j]);break; //尽可能减少循环次数} else if (s[i] == right[j]) {if (!st.empty()) {char top = st.top();if (top == left[j]) {st.pop();} else {return false;}}else{return false;}break;}}}//如果还有没匹配的剩余字符,那么说明字符串无效if (st.empty()) {return true;}return false;}
};