Minimize length of a string by removing pairs of consecutive increasing or decreasing digits | C # 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
using System ; using System . Collections . Generic ; class GFG { static int minLength ( String S ) { Stack < char > st = new Stack < char > ( ) ; foreach ( char ch in S . ToCharArray ( ) ) { if ( st . Count == 0 ) st . Push ( ch ) ; else { char top = st . Peek ( ) ; if ( Math . Abs ( ch - top ) == 1 ) st . Pop ( ) ; else { st . Push ( ch ) ; } } } return st . Count ; } public static void Main ( String [ ] args ) { String S = "12213" ; Console . WriteLine ( minLength ( S ) ) ; } }