有效的括号
题目链接
class Solution {
public:
bool isValid(string s) {
stack<char> st;
unordered_map<char, char> hash={{')','('}, {']','['}, {'}','{'}};
for(auto c:s){
if(hash.count(c)==0){
st.push(c);
}
else if(!st.empty()&&hash[c]==st.top()){
st.pop();
}
else return false;
}
return st.empty();
}
};
有效括号升级版
题目链接
class Solution {
public:
bool checkValidString(string s) {
stack<int> star;
stack<int> left;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (c == '(') {
left.push(i);
}
if (c == '*') {
star.push(i);
}
if (c == ')') {
if (!left.empty()) {
left.pop();
} else if (!star.empty()) {
star.pop();
} else {
return false;
}
}
}
while (!left.empty()) {
int posL = left.top();
if (star.empty()) return false;
int posS = star.top();
if (posS > posL) {
star.pop();
left.pop();
} else {
return false;
}
}
return true;
}
};