LeeCode 20.有效的括号
问题:
源程序加上了自己的注释
bool isValid(string s) // Leecode 20
{
if (s.size() % 2 == 1)
return false;
unordered_map<char, char> pairs = { //哈希表的键为右括号,值为相同类型的左括号
{')','('},
{']','['},
{'}','{'}
};
stack<char> sta;
for (char c : s) // 遍历字符串
{
if (pairs.count(c)) // 统计关键字为 c 的数据个数,如果有则返回1
{
if (sta.empty() || sta.top() != pairs[c]) //判断栈中是否还有未匹配符号,及栈顶符号是否与当前键对应的值相等。pairs[key]=value
return false;
sta.pop();
}
else
sta.push(c);
}
return sta.empty(); //匹配完成后,再次检查栈中元素是否已清空
}
unordered_map::count(key)
原型:size_type count ( const key_type& k ) const; 查找键值为key的值,如果有就返回1,否则返回0
我认为比较巧妙的地方在于用右括号作为键,左括号为值。