leetcode 热题 Hot 100-2. 有效的括号
- 题目
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
- 思路
- 经典题目,使用栈进行括号匹配验证
- 时间复杂度分析O(n)
- 代码
class Solution {
public:
bool isValid(string s) {
stack<char> temp;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
temp.push(s[i]);
} else {
if (temp.empty())
return false;
if (s[i] == ')') {
if (temp.top() != '(')
return false;
temp.pop();
} else if (s[i] == '}') {
if (temp.top() != '{')
return false;
temp.pop();
} else if (s[i] == ']') {
if (temp.top() != '[')
return false;
temp.pop();
}
}
}
if (temp.empty())
return true;
return false;
}
};