congr / world

2 stars 1 forks source link

LeetCode : 678. Valid Parenthesis String #499

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/valid-parenthesis-string/

image

congr commented 5 years ago
class Solution {
    public boolean checkValidString(String s) {
        if (s.isEmpty()) return true;

        return check(s.toCharArray(), 0, 0);
    }

    boolean check(char[] ch, int p, int cnt) {
        if (p == ch.length) return cnt == 0;
        if (cnt < 0) return false; // !!! cnt can't be negative. ()) case

        if (ch[p] == '(') return check(ch, p+1, cnt+1);
        else if (ch[p] == ')') return check(ch, p+1, cnt-1);
        else return check(ch, p+1, cnt) ||   // '*' is empty
                    check(ch, p+1, cnt+1) || // '*' is '('
                    check(ch, p+1, cnt-1);   // '*' is ')'
    }
}