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 char 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
using System ; using System . Collections . Generic ; class GFG { static bool Formatted ( String s ) { List < char > k = new List < char > ( ) ; int i = 0 ; while ( i < s . Length ) { if ( s [ i ] == ' ) ' || s [ i ] == ' ( ' ) { k . Add ( s [ i ] ) ; i += 1 ; } else { char st = ' \x0000' ; while ( s [ i ] != ' ) ' && s [ i ] != ' ) ' ) { st = s [ i ] ; i = i + 1 ; } k . Add ( st ) ; } } int depth = 0 , flag = 1 ; int open = 0 , close = 0 ; foreach ( char i2 in k ) { if ( i2 == ' ( ' ) { depth += 1 ; open += 1 ; } else if ( i2 == ' ) ' ) { depth -= 1 ; close += 1 ; } else { if ( i2 - '0' != depth ) { flag = 0 ; break ; } } } if ( open != close ) flag = 0 ; return ( flag == 1 ) ? true : false ; } public static void Main ( String [ ] args ) { String s = " ( (2 ) ( (3 ) ) ) " ; bool k = Formatted ( s ) ; if ( k == true ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }