其他分享
首页 > 其他分享> > [leetcode] 678. Valid Parenthesis String

[leetcode] 678. Valid Parenthesis String

作者:互联网

Description

Given a string containing only three types of characters: ‘(’, ‘)’ and ‘*’, write a function to check whether this string is valid. We define the validity of a string by these rules:

Any left parenthesis ‘(’ must have a corresponding right parenthesis ‘)’.
Any right parenthesis ‘)’ must have a corresponding left parenthesis ‘(’.
Left parenthesis ‘(’ must go before the corresponding right parenthesis ‘)’.
‘*’ could be treated as a single right parenthesis ‘)’ or a single left parenthesis ‘(’ or an empty string.
An empty string is also valid.
Example 1:
Input:

"()"

Output:

True

Example 2:
Input:

"(*)"

Output:

True

Example 3:
Input:

"(*))"

Output:

True

Note:

  1. The string size will be in the range [1, 100].

分析

题目的意思是:验证一个字符串是否是合法字符串。

代码

class Solution {
public:
    bool checkValidString(string s) {
        stack<int> s1,star;
        for(int i=0;i<s.length();i++){
            if(s[i]=='('){
                s1.push(i);
            }else if(s[i]==')'){
                if(s1.empty()&&star.empty()){
                    return false;
                }
                if(s1.empty()&&!star.empty()){
                    star.pop();
                }else{
                   s1.pop(); 
                }
                
            }else{
                star.push(i);
            }
        }
        while(!s1.empty()&&!star.empty()){
            if(s1.top()>star.top()){
                return false;
            }
            star.pop();
            s1.pop();
        }
        return s1.empty();
    }
};

参考文献

[LeetCode] Valid Parenthesis String 验证括号字符串

标签:right,678,String,s1,Valid,parenthesis,True,Example,string
来源: https://blog.csdn.net/w5688414/article/details/97622594