Calculate score for the given binary string | Java implementation of the approach ; Function to return the score for the given binary string ; Traverse through string character ; Initialize current chunk 's size ; Get current character ; Calculate total chunk size of same characters ; Add / subtract pow ( chunkSize , 2 ) depending upon character ; Return the score ; Driver code
class GFG { public static int calcScore ( String str ) { int score = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; ) { int chunkSize = 1 ; char currentChar = str . charAt ( i ++ ) ; while ( i < len && str . charAt ( i ) == currentChar ) { chunkSize ++ ; i ++ ; } if ( currentChar == '1' ) score += Math . pow ( chunkSize , 2 ) ; else score -= Math . pow ( chunkSize , 2 ) ; } return score ; } public static void main ( String [ ] args ) { String str = "11011" ; System . out . println ( calcScore ( str ) ) ; } }