Number of substrings having an equal number of lowercase and uppercase letters | Java program for the above approach ; Function to find the count of substrings having an equal number of uppercase and lowercase characters ; Stores the count of prefixes having sum S considering uppercase and lowercase characters as 1 and - 1 ; Stores the count of substrings having equal number of lowercase and uppercase characters ; Stores the sum obtained so far ; If the character is uppercase ; Otherwise ; If currsum is 0 ; If the current sum exists in the HashMap prevSum ; Increment the resultant count by 1 ; Update the frequency of the current sum by 1 ; Return the resultant count of the subarrays ; Driver Code
import java . util . HashMap ; class GFG { static int countSubstring ( String S , int N ) { HashMap < Integer , Integer > prevSum = new HashMap < > ( ) ; int res = 0 ; int currentSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S . charAt ( i ) >= ' A ' && S . charAt ( i ) <= ' Z ' ) { currentSum ++ ; } else currentSum -- ; if ( currentSum == 0 ) res ++ ; if ( prevSum . containsKey ( currentSum ) ) { res += prevSum . get ( currentSum ) ; } prevSum . put ( currentSum , prevSum . getOrDefault ( currentSum , 0 ) + 1 ) ; } return res ; } public static void main ( String [ ] args ) { String S = " gEEk " ; System . out . println ( countSubstring ( S , S . length ( ) ) ) ; } }