Check if the Depth of Parentheses is correct in the given String | Function to check if the Depth of Parentheses is correct in the given String ; Appending if the Character is not integer ; Iterating till the entire Digit is read ; Check if character is ' ( ' ; Increment depth by 1 ; Increment open by 1 ; Check if character is ' ) ' ; Decrement depth by 1 ; Increment close by 1 ; Check if open parentheses NOT equals close parentheses ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool Formatted ( string s ) { vector < char > k ; int i = 0 ; while ( i < s . size ( ) ) { if ( s [ i ] == ' ) ' or s [ i ] == ' ( ' ) { k . push_back ( s [ i ] ) ; i += 1 ; } else { char st ; while ( s [ i ] != ' ) ' and s [ i ] != ' ) ' ) { st = s [ i ] ; i = i + 1 ; } k . push_back ( st ) ; } } int depth = 0 , flag = 1 ; int open = 0 , close = 0 ; for ( char i : k ) { if ( i == ' ( ' ) { depth += 1 ; open += 1 ; } else if ( i == ' ) ' ) { depth -= 1 ; close += 1 ; } else { if ( i - '0' != depth ) { flag = 0 ; break ; } } } if ( open != close ) flag = 0 ; return ( flag == 1 ) ? true : false ; } int main ( ) { string s = " ( (2 ) ( (3 ) ) ) " ; bool k = Formatted ( s ) ; if ( k == true ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; }