Make The String Great

Make The String Great

Given a string s of lower and upper case English letters.

A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:

  • 0 <= i <= s.length - 2

  • s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.

To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.

Return the string after making it good. The answer is guaranteed to be unique under the given constraints.

Notice that an empty string is also good.

LeetCode Problem - 1544

class Solution {
    // Method to remove adjacent characters with the same letter but different cases
    public String makeGood(String s) {
        // Using a stack to keep track of characters
        Stack<Character> stack = new Stack<>();
        // Iterating through each character in the string
        for (char c : s.toCharArray()) {
            // If the stack is not empty and the current character and the character on top of the stack form a pair of letters with different cases (ASCII difference is 32)
            if (!stack.isEmpty() && Math.abs(c - stack.peek()) == 32) {
                // Pop the character from the stack
                stack.pop();
            } else {
                // Otherwise, push the character onto the stack
                stack.push(c);
            }
        }

        // Reconstructing the string from the characters remaining in the stack
        StringBuilder sb = new StringBuilder();
        // Iterating through the characters in the stack
        while (!stack.isEmpty()) {
            // Appending the character to the StringBuilder
            sb.append(stack.peek());
            // Popping the character from the stack
            stack.pop();
        }

        // Reversing the StringBuilder and converting it to a string
        return sb.reverse().toString();
    }
}

Did you find this article valuable?

Support Gulshan Kumar by becoming a sponsor. Any amount is appreciated!