做leetcode第20题第一次用到unordered_map,写了两次还是不怎么会,很多内容都是第一次接触,这里记录一下。
class Solution {
public:
bool isValid(string s) {
unordered_map<char, int> m {
{'(', 1}, {'[', 2},
{'{', 3}, {')', 4},
{']', 5}, {'}', 6}
};
stack<char> st;
bool isture = true;
for (char x : s) {
int flag = m[x];
if (flag >= 1 && flag <= 3) {
st.push(x);
} else if (!st.empty() && m[st.top()] == flag - 3) {
st.pop();
} else {
isture = false;
break;
}
}
if (!st.empty()) {
isture = false;
}
return isture;
}
};