Minimize length of a string by removing pairs of consecutive increasing or decreasing digits | 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
def minLength ( S ) : NEW_LINE INDENT st = [ ] NEW_LINE for ch in S : NEW_LINE INDENT if ( len ( st ) == 0 ) : NEW_LINE INDENT st . append ( ch ) NEW_LINE DEDENT else : NEW_LINE INDENT top = st [ - 1 ] NEW_LINE if ( abs ( ord ( ch ) - ord ( top ) ) == 1 ) : NEW_LINE INDENT st . pop ( ) NEW_LINE DEDENT else : NEW_LINE INDENT st . append ( ch ) NEW_LINE DEDENT DEDENT DEDENT return len ( st ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "12213" NEW_LINE print ( minLength ( S ) ) NEW_LINE DEDENT