题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0cdee0a6f972facdc1b4042408830a41.png)
Leetcode 678. 有效的括号字符串
代码(9.6 首刷看解析)
class Solution {
public:
bool checkValidString(string s) {
stack<int> chr_sk, star_sk;
for(int i = 0; i < s.size(); i++) {
if(s[i] == ')') {
if(star_sk.empty() && chr_sk.empty()) {
return false;
} else if(!chr_sk.empty()) {
chr_sk.pop();
} else {
star_sk.pop();
}
} else if(s[i] == '*') {
star_sk.push(i);
} else {
chr_sk.push(i);
}
}
while(!chr_sk.empty()) {
if(star_sk.empty())
return false;
int star_idx = star_sk.top();
star_sk.pop();
int chr_idx = chr_sk.top();
chr_sk.pop();
if(star_idx < chr_idx)
return false;
}
return true;
}
};
代码(10.7 二刷自解)
class Solution {
public:
bool checkValidString(string s) {
vector<int> charStack, starStack;
for(int i = 0; i < s.size(); i++) {
char c = s[i];
if(c == ')') {
if(charStack.empty() && starStack.empty())
return false;
else if(!charStack.empty()) {
charStack.pop_back();
} else {
starStack.pop_back();
}
} else if(c == '*') {
starStack.push_back(i);
} else {
charStack.push_back(i);
}
}
while(!charStack.empty()) {
if(starStack.empty())
return false;
int charIndex = charStack.back();
int starIndex = starStack.back();
if(charIndex > starIndex)
return false;
charStack.pop_back();
starStack.pop_back();
}
return true;
}
};