Reduce string by removing outermost parenthesis from each primitive substring | Java program to implement the above approach ; Function to remove the outermost parentheses of every primitive substring from the given string ; Stores the resultant string ; Stores the count of opened parentheses ; Traverse the string ; If opening parenthesis is encountered and their count exceeds 0 ; Include the character ; If closing parenthesis is encountered and their count is less than count of opening parentheses ; Include the character ; Return the resultant string ; Driver Code
import java . io . * ; class GFG { static String removeOuterParentheses ( String S ) { String res = " " ; int count = 0 ; for ( int c = 0 ; c < S . length ( ) ; c ++ ) { if ( S . charAt ( c ) == ' ( ' && count ++ > 0 ) res += S . charAt ( c ) ; if ( S . charAt ( c ) == ' ) ' && count -- > 1 ) res += S . charAt ( c ) ; } return res ; } public static void main ( String [ ] args ) { String S = " ( ( ) ( ) ) ( ( ) ) ( ) " ; System . out . print ( removeOuterParentheses ( S ) ) ; } }