Remove Invalid Parentheses | method checks if character is parenthesis ( openor closed ) ; method returns true if string contains valid parenthesis ; method to remove invalid parenthesis ; visit set to ignore already visited string ; queue to maintain BFS ; pushing given string as starting node into queue ; If answer is found , make level true so that valid string of only that level are processed . ; Removing parenthesis from str and pushing into queue , if not visited already ; Driver Code
function isParenthesis ( c ) { return ( ( c == ' ' ) || ( c == ' ' ) ) ; } function isValidString ( str ) { let cnt = 0 ; for ( let i = 0 ; i < str . length ; i ++ ) { if ( str [ i ] == ' ' ) cnt ++ ; else if ( str [ i ] == ' ' ) cnt -- ; if ( cnt < 0 ) return false ; } return ( cnt == 0 ) ; } function removeInvalidParenthesis ( str ) { if ( str . length == 0 ) return ; let visit = new Set ( ) ; let q = [ ] ; let temp ; let level = false ; q . push ( str ) ; visit . add ( str ) ; while ( q . length != 0 ) { str = q . shift ( ) ; if ( isValidString ( str ) ) { document . write ( str + " " ) ; level = true ; } if ( level ) continue ; for ( let i = 0 ; i < str . length ; i ++ ) { if ( ! isParenthesis ( str [ i ] ) ) continue ; temp = str . substring ( 0 , i ) + str . substring ( i + 1 ) ; if ( ! visit . has ( temp ) ) { q . push ( temp ) ; visit . add ( temp ) ; } } } } let expression = " " ; removeInvalidParenthesis ( expression ) ; expression = " " ; removeInvalidParenthesis ( expression ) ;