class Solution {
public:
bool isValid(string s) {
stack<char> st;//为什么要使用栈?栈是先进后出的,一一对应,与括号的匹配类似
unordered_map<char, int>m{ { '(', 1 }, { '{', 2 }, { '[', 3 }, { ')', 4 }, { '}', 5 }, { ']', 6 } };//用无序的map,查找效率更高。若不用map,一个一个来检查是什么符号的话
//这里是要用给出的char去“寻找”。 //并且去做相应的操作,很繁杂。用map可以提供一个标志数化简流程。
for (char c : s)
{
int flag = m[c];
if (flag <= 3 && flag >= 1)
{
st.push(c);
}
else if (!st.empty() && m[st.top()] + 3 == flag)//利用map的另一个变量去匹配
{
st.pop();
}
else
{
return false;
}
}
if (!st.empty())
{
return false;
}
else
{
return true;
}
}
};