Minimize length of a string by removing pairs of consecutive increasing or decreasing digits | java program for the above approach ; Function to find the minimum length of the string possible after removing pairs of consecutive digits ; Initialize the stack st ; Traverse the string S ; If the stack is empty ; Otherwise ; Get the top character of the stack ; If cha and top are consecutive digits ; Otherwise , push the character ch ; Print the size of the stack ; Driver Code
import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static int minLength ( String S ) { Stack < Character > st = new Stack < > ( ) ; for ( char ch : S . toCharArray ( ) ) { if ( st . isEmpty ( ) ) st . push ( ch ) ; else { char top = st . peek ( ) ; if ( Math . abs ( ch - top ) == 1 ) st . pop ( ) ; else { st . push ( ch ) ; } } } return st . size ( ) ; } public static void main ( String [ ] args ) { String S = "12213" ; System . out . println ( minLength ( S ) ) ; } }