20. Valid Parentheses
Runtime: 4 ms
Memory Usage: 8.7 MB
/*
* @lc app=leetcode id=20 lang=cpp
*
* [20] Valid Parentheses
*/
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(int i = 0; i < s.size(); i++){
if(!st.empty()){
if((st.top() == '(' && s[i] == ')') || (st.top() == '{' && s[i] == '}') || (st.top() == '[' && s[i] == ']')){
st.pop();
}else
{
st.push(s[i]);
}
}else
{
st.push(s[i]);
}
}
if(!st.empty()){
return false;
}else{
return true;
}
}
};
本文介绍了一种使用栈数据结构解决LeetCode第20题的有效括号匹配问题的方法。通过遍历输入字符串,算法能够判断括号是否正确配对,最后返回布尔值结果。该算法在LeetCode上的运行时间为4ms,内存使用为8.7MB。
306

被折叠的 条评论
为什么被折叠?



