Count special palindromes in a String | Function to count special Palindromic susbstring ; store count of special Palindromic substring ; it will store the count of continues same char ; traverse string character from left to right ; store same character count ; count smiler character ; Case : 1 so total number of substring that we can generate are : K * ( K + 1 ) / 2 here K is sameCharCount ; store current same char count in sameChar [ ] array ; increment i ; Case 2 : Count all odd length Special Palindromic substring ; if current character is equal to previous one then we assign Previous same character count to current one ; case 2 : odd length ; subtract all single length substring ; Driver Code
< ? php function CountSpecialPalindrome ( $ str ) { $ n = strlen ( $ str ) ; $ result = 0 ; $ sameChar = array_fill ( 0 , $ n , 0 ) ; $ i = 0 ; while ( $ i < $ n ) { $ sameCharCount = 1 ; $ j = $ i + 1 ; while ( $ j < $ n ) { if ( $ str [ $ i ] != $ str [ $ j ] ) break ; $ sameCharCount ++ ; $ j ++ ; } $ result += ( int ) ( $ sameCharCount * ( $ sameCharCount + 1 ) / 2 ) ; $ sameChar [ $ i ] = $ sameCharCount ; $ i = $ j ; } for ( $ j = 1 ; $ j < $ n ; $ j ++ ) { if ( $ str [ $ j ] == $ str [ $ j - 1 ] ) $ sameChar [ $ j ] = $ sameChar [ $ j - 1 ] ; if ( $ j > 0 && $ j < ( $ n - 1 ) && ( $ str [ $ j - 1 ] == $ str [ $ j + 1 ] && $ str [ $ j ] != $ str [ $ j - 1 ] ) ) $ result += $ sameChar [ $ j - 1 ] < $ sameChar [ $ j + 1 ] ? $ sameChar [ $ j - 1 ] : $ sameChar [ $ j + 1 ] ; } return $ result - $ n ; } $ str = " abccba " ; echo CountSpecialPalindrome ( $ str ) ; ? >