给出一个字符串中只有三个类型的字符:"("",") 和"*",写一个函数来检查这个字符串是否有效.我们通过以下规则来定义字符串的有效性:任何左括号"("必须有一个相应的右括号") ".任何右括号"") "必须有一个相应的左括号"(".左括号"("必须在相应的右括号"之前). "*"可以被视为单一右括号")) "或单一左括号"("或空字符串.空字符串也有效.
建议这个Leetcode问题的解决方案,然后在python中实现.
One approach is to use a stack to keep track of the opening parentheses and the asterisks. Whenever a closing parenthesis is encountered, the stack is checked in the following order: match it with an opening parenthesis on top of the stack, if not match it with an asterisk on top of the stack, if not return False. At the end, if the stack still contains opening parentheses, then it is also invalid.

Here's the implementation in Python:

```
def checkValidString(s: str) -> bool:
    stack = []
    asterisk = []
    for i, char in enumerate(s):
        if char == '(':
            stack.append(i)
        elif char == '*':
            asterisk.append(i)
        else: #closing parenthesis
            if not stack and not asterisk:
                return False
            elif stack:
                stack.pop()
            else: #use asterisk as opening parenthesis
                asterisk.pop()
    while stack and asterisk:
        if stack.pop() > asterisk.pop():
            return False
    return not stack #if there's no more opening parenthesis left, it's valid
```