当前位置:网站首页>Niuke's brush question -- judgment of legal bracket sequence

Niuke's brush question -- judgment of legal bracket sequence

2022-06-11 18:29:00 HHYX.

Topic link : Legal bracket sequence judgment

Title Description

describe
Given a string A And its length n, Please return one bool The value represents whether it is a legal string of parentheses ( Can only consist of parentheses ).

The test sample :
 Insert picture description here

Topic analysis

In the question is to judge whether the brackets are reasonable
There are several possibilities for unsuccessful matching :

  1. The current character is not a bracket , In this case, you can return directly false
  2. Incomplete bracket match , A single left or right parenthesis appears
    Here you can use a stack to store strings , If the left bracket is encountered, it will be put on the stack , If the right bracket is encountered, judge whether there is a matching left bracket at the top of the stack , If so, the top element of the stack is pushed out of the stack , If not, the match is incomplete , More than the right half . If the last stack is empty , It means that there are matching parentheses . If the stack is not empty, it indicates that there are extra left parentheses
    The code implementation is as follows :

Code implementation

 bool chkParenthesis(string A, int n) {
    
        // write code here
        stack<char> cp;
        for(size_t i=0;i<A.size();i++)
        {
    
            if(A[i]=='(')
            {
    
                cp.push(A[i]);
            }
            else if(A[i]==')')
            {
    
                if(!cp.empty() && cp.top()=='(')
                {
    
                    cp.pop();// If it is a matching left parenthesis, it will be out of the stack 
                }
                else
                {
    
                    return false;
                }
            }
            else
            {
    
                return false;
            }
        }
        if(cp.empty())
        {
    
            return true;
        }
        else
        {
    
            return false;
        }
    }

 Insert picture description here

原网站

版权声明
本文为[HHYX.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111814367203.html