Find numbers of balancing positions in string | PHP program to find number of balancing points in string ; function to return number of balancing points ; hash array for storing hash of string initialized by 0 being global ; process string initially for rightVisited ; check for balancing points ; for every position inc left hash & dec rightVisited ; check whether both hash have same character or not ; Either both leftVisited [ j ] and rightVisited [ j ] should have none zero value or both should have zero value ; if both have same character increment count ; Driver Code
< ? php $ MAX_CHAR = 256 ; function countBalance ( $ str ) { global $ MAX_CHAR ; $ leftVisited = array_fill ( 0 , $ MAX_CHAR , NULL ) ; $ rightVisited = array_fill ( 0 , $ MAX_CHAR , NULL ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ rightVisited [ ord ( $ str [ $ i ] ) ] ++ ; $ res = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ leftVisited [ ord ( $ str [ $ i ] ) ] ++ ; $ rightVisited [ ord ( $ str [ $ i ] ) ] -- ; for ( $ j = 0 ; $ j < $ MAX_CHAR ; $ j ++ ) { if ( ( $ leftVisited [ $ j ] == 0 && $ rightVisited [ $ j ] != 0 ) || ( $ leftVisited [ $ j ] != 0 && $ rightVisited [ $ j ] == 0 ) ) break ; } if ( $ j == $ MAX_CHAR ) $ res ++ ; } return $ res ; } $ str = " abaababa " ; echo countBalance ( $ str ) ; ? >