Reduce the string to minimum length with the given operation | Java implementation of the approach ; Function to return the minimum possible length str can be reduced to with the given operation ; Stack to store the characters of the given string ; For every character of the string ; If the stack is empty then push the current character in the stack ; Get the top character ; If the top element is not equal to the current element and it only differs in the case ; Pop the top element from stack ; Else push the current element ; Driver code
import java . util . * ; class GFG { static int minLength ( String str , int len ) { Stack < Character > s = new Stack < Character > ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( s . empty ( ) ) { s . push ( str . charAt ( i ) ) ; } else { char c = s . peek ( ) ; if ( c != str . charAt ( i ) && Character . toUpperCase ( c ) == Character . toUpperCase ( ( str . charAt ( i ) ) ) ) { s . pop ( ) ; } else { s . push ( str . charAt ( i ) ) ; } } } return s . size ( ) ; } public static void main ( String [ ] args ) { String str = " ASbBsd " ; int len = str . length ( ) ; System . out . println ( minLength ( str , len ) ) ; } }