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
import java . util . * ; class GFG { static boolean Formatted ( String s ) { Vector < Character > k = new Vector < Character > ( ) ; int i = 0 ; while ( i < s . length ( ) ) { if ( s . charAt ( i ) == ' ) ' || s . charAt ( i ) == ' ( ' ) { k . add ( s . charAt ( i ) ) ; i += 1 ; } else { char st = 0 ; while ( s . charAt ( i ) != ' ) ' && s . charAt ( i ) != ' ) ' ) { st = s . charAt ( i ) ; i = i + 1 ; } k . add ( st ) ; } } int depth = 0 , flag = 1 ; int open = 0 , close = 0 ; for ( char i2 : 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 ) ) ) " ; boolean k = Formatted ( s ) ; if ( k == true ) System . out . printf ( " Yes " ) ; else System . out . printf ( " No " ) ; } }