Reduce the string to minimum length with the given operation - GeeksforGeeks

13 Aug, 2021
Given a string str consisting of lowercase and uppercase characters, the task is to find the minimum possible length the string can be reduced to after performing the given operation any number of times. In a single operation, any two consecutive characters can be removed if they represent the same character in different cases i.e. “aA” and “Cc” can be removed but “cc” and “EE” cannot be removed.Examples:  
Input: str = “ASbBsd” Output: 2 Operations 1: “ASbBsd” -> “ASsd” Operations 2: “ASsd” -> “Ad” The string cannot be reduced further.Input: str = “AsSaDda” Output: 1 Operations 1: “AsSaDda” -> “AaDda” Operations 2: “AaDda” -> “Dda” Operations 3: “Dda” -> “a”  
 
Approach:  
Create a stack to store the characters of the string.
For every character of the string starting from the first character, if the stack is empty then push the current character in the stack.
Else match the current character with the top of the stack, if they only differ in the case then pop the element from the stack and continue.
If they are not equal then push the current element to the stack and repeat the above steps for the rest of the string.
The size of the stack in the end is the required answer.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum// possible length str can be reduced// to with the given operationint minLength(string str, int len){     // Stack to store the characters    // of the given string    stack<char> s;     // For every character of the string    for (int i = 0; i < len; i++) {         // If the stack is empty then push the        // current character in the stack        if (s.empty()) {            s.push(str[i]);        }        else {             // Get the top character            char c = s.top();             // If the top element is not equal            // to the current element and it            // only differs in the case            if (c != str[i]                && toupper(c) == toupper(str[i])) {                 // Pop the top element from stack                s.pop();            }             // Else push the current element            else {                s.push(str[i]);            }        }    }     return s.size();} // Driver codeint main(){    string str = "ASbBsd";    int len = str.length();     cout << minLength(str, len);     return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the minimum// possible length str can be reduced// to with the given operationstatic int minLength(String str, int len){     // Stack to store the characters    // of the given string    Stack<Character> s = new Stack<Character>();     // For every character of the string    for (int i = 0; i < len; i++)    {         // If the stack is empty then push the        // current character in the stack        if (s.empty())        {            s.push(str.charAt(i));        }        else        {             // Get the top character            char c = s.peek();             // If the top element is not equal            // to the current element and it            // only differs in the case            if (c != str.charAt(i) &&                Character.toUpperCase(c) ==                Character.toUpperCase((str.charAt(i))))            {                 // Pop the top element from stack                s.pop();            }             // Else push the current element            else            {                s.push(str.charAt(i));            }        }    }    return s.size();} // Driver codepublic static void main(String []args){    String str = "ASbBsd";    int len = str.length();     System.out.println(minLength(str, len));}} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Function to return the minimum# possible length str can be reduced# to with the given operationdef minLength(string, l) :     # Stack to store the characters    # of the given string    s = [];     # For every character of the string    for i in range(l) :         # If the stack is empty then push the        # current character in the stack        if (len(s) == 0) :            s.append(string[i]);                     else :             # Get the top character            c = s[-1];                         # If the top element is not equal            # to the current element and it            # only differs in the case            if (c != string[i] and                c.upper() == string[i].upper()) :                 # Pop the top element from stack                s.pop();             # Else push the current element            else :                s.append(string[i]);     return len(s); # Driver codeif __name__ == "__main__" :     string = "ASbBsd";    l = len(string);     print(minLength(string, l)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the minimum// possible length str can be reduced// to with the given operationstatic int minLength(String str, int len){     // Stack to store the characters    // of the given string    Stack<char> s = new Stack<char>();     // For every character of the string    for (int i = 0; i < len; i++)    {         // If the stack is empty then push the        // current character in the stack        if (s.Count==0)        {            s.Push(str[i]);        }        else        {             // Get the top character            char c = s.Peek();             // If the top element is not equal            // to the current element and it            // only differs in the case            if (c != str[i] &&                char.ToUpper(c) ==                char.ToUpper((str[i])))            {                 // Pop the top element from stack                s.Pop();            }             // Else push the current element            else            {                s.Push(str[i]);            }        }    }    return s.Count;} // Driver codepublic static void Main(String []args){    String str = "ASbBsd";    int len = str.Length;     Console.WriteLine(minLength(str, len));}} // This code is contributed by PrinciRaj1992
<script>    // Javascript implementation of the approach         // Function to return the minimum    // possible length str can be reduced    // to with the given operation    function minLength(str, len)    {         // Stack to store the characters        // of the given string        let s = [];         // For every character of the string        for (let i = 0; i < len; i++)        {             // If the stack is empty then push the            // current character in the stack            if (s.length==0)            {                s.push(str[i]);            }            else            {                 // Get the top character                let c = s[s.length - 1];                 // If the top element is not equal                // to the current element and it                // only differs in the case                if (c != str[i] &&                    c.toUpperCase() ==                    str[i].toUpperCase())                {                     // Pop the top element from stack                    s.pop();                }                 // Else push the current element                else                {                    s.push(str[i]);                }            }        }        return s.length;    }         let str = "ASbBsd";    let len = str.length;       document.write(minLength(str, len)); </script>
2
 
Time Complexity: O(N).Auxiliary Space: O(N). 
Rajput-Ji
princiraj1992
ankthon
decode2207
pankajsharmagfg
Data Structures
Stack
Strings
Data Structures
Strings
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Introduction to Tree Data Structure
Differences and Applications of List, Tuple, Set and Dictionary in Python
Stack Data Structure (Introduction and Program)
Stack in Python
Stack Class in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Queue using Stacks