力扣题:https://leetcode-cn.com/problems/valid-parenthesis-string/
class Solution {
public boolean checkValidString(String s) {
int cnt1 = 0,cnt2 = 0,cnt3 = 0;
int cnt4;
for (int i = 0;i < s.length();i++){
if (s.charAt(i)=='('){
cnt1++;
}
if (s.charAt(i)==')'){
cnt2++;
}
if (s.charAt(i)=='*'){
cnt3++;
}
}
if (cnt1 == cnt2){
return true;
}else if(cnt1 > cnt2){
cnt4 = cnt1 - cnt2;
if(cnt3 >= cnt4){
return true;
}
}else {
cnt4 = cnt2 - cnt1;
if(cnt3 >= cnt4){
return true;
}
}
return false;
}
}
这是我自己本来的思路,但我只考虑到了左右括号数量上的问题,但忘记考虑了左括号要在右括号的左边这个问题,所以这个问题就没有得到解决,然后我就在题解里找到一个和我的思路有点相似的而且正确的方法学习了一下。
正确的代码如下
class Solution {
//从0开始遍历,有一个右括号,就必须有一个左括号或者星号和它匹配,否则返回false。
//从结尾开始遍历,有一个左括号,就必须有一个右括号或者星号和它匹配,否则返回false。
public boolean checkValidString(String s) {
int left = 0;
int right = 0;
int star = 0;
//从0开始遍历
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '(') {
left++;
}else if(c == ')') {
right++;
}else {
star++;
}
if(right > 0) {
if(left > 0) {
left--;
right--;
}else if(star > 0) {
star--;
right--;
}else {
return false;
}
}
}
left = 0;
right = 0;
star = 0;
//从结尾开始遍历
for(int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i);
if(c == '(') {
left++;
}else if(c == ')') {
right++;
}else {
star++;
}
if(left > 0) {
if(right > 0) {
left--;
right--;
}else if(star > 0) {
star--;
left--;
}else {
return false;
}
}
}
return true;
}
}