leetcode 20. 有效的括号 easy
题目描述:
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
解题思路:
没什么好说的,用栈就好
代码:
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
unordered_map<char, char> hash = {{'(',')'},{'[',']'},{'{','}'}};
for (char &c: s)
{
if (hash.count(c))
stk.push(c);
else
{
if (stk.empty() || hash[stk.top()] != c)
return false;
stk.pop();
}
}
return stk.empty();
}
};

本文详细解析了LeetCode上第20题“有效的括号”的解题思路与代码实现,通过使用栈和哈希表的数据结构,高效地判断字符串中的括号是否正确配对。

301

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



