Validity of bracketed strings

Validity of bracketed strings

Title description

Given a string str, judge whether it is an overall valid bracket string (the overall valid: that is, there is a bracket matching scheme, so that each bracket character can find the corresponding reverse bracket, and the string does not contain non-parentheses character).

Enter a description:

The input contains one line, representing str (1 ≤ lengthstr ≤ 1 0 5) str(1 \leq length_{str} \leq 10^5)str(1lengthstr105)

Output description:

Output one line, if str is a valid bracket string, output "YES", otherwise output "NO".

Example 1
enter
(())
Output
YES
Example 2
enter
()a()
Output
NO
Description
()a()中包含了 ‘a’,a不是括号字符
Remarks:

Time complexity O (n) O(n)O ( n ) , additional space complexityO (1) O(1)O ( 1 )


answer:

Scan from front to back, use a counter to record the number of left parentheses, and return directly if it encounters a non-parenthesis character; otherwise, the counter will increase by one when it encounters a left parenthesis. When a right parenthesis is encountered, if the number of left parentheses equals 0, it is illegal. Just return directly, otherwise the number of left parentheses is reduced by one, which means a bunch of parentheses are paired.

Code:
#include <cstdio>
#include <cstring>

using namespace std;

int main(void) {
    
    
    char ch;
    int left = 0;
    while ((ch = getchar()) != '\n') {
    
    
        if (ch != '(' && ch != ')') return 0 * puts("NO");
        if (ch == ')' && --left < 0) {
    
    
            return 0 * puts("NO");
        } else if (ch == '(') ++left;
    }
    puts(left ? "NO" : "YES");
    return 0;
}

Guess you like

Origin blog.csdn.net/MIC10086/article/details/108902270