20. 有效的括号
题目:
栈(可以在判断栈长度大于剩余长度时直接退出false)
class Solution20 {
public:
bool isValid(string s) {
if (s == "") {
return true;
}
if (s.length() % 2 != 0) {
return false;
}
stack st;
int i = 0;
for (const char& ch : s) {
if (st.empty() || ch == '(' || ch == '[' || ch == '{') {
st.push(ch);
} else if ((ch == ')' && st.top() == '(') || (ch == ']' && st.top() == '[') ||
(ch == '}' && st.top() == '{')) {
st.pop();
} else {
return false;
}
i++;
}
return true;
}
};
1111. 有效括号的嵌套深度