Skip to main content

Make The String Great - LeetCode Daily Challenge

Prerna Sharma

Problem Statement

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.

Example 1

Input: s = "leEeetcode"
Output: "leetcode"

Example 2

Input: s = "abBAcC"
Output: ""

Try here before watching the video.

Video Solution

Java Code

class Solution {
    public String makeGood(String s) {
        Stack<Character> stack = new Stack<>();
        for(char ch : s.toCharArray()) {
            if(!stack.isEmpty() && Math.abs(stack.peek() - ch) == 32) {
                stack.pop();
            } else {
                stack.push(ch);
            }
        }

        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty()) {
            sb.append(stack.pop());
        }

        return sb.reverse().toString();
    }
}

C++ Code

class Solution {
public:
    string makeGood(string s) {
        stack<char> stack;
        for (char ch : s) {
            if (!stack.empty() && abs(stack.top() - ch) == 32) {
                stack.pop();
            } else {
                stack.push(ch);
            }
        }

        string result;
        while (!stack.empty()) {
            result += stack.top();
            stack.pop();
        }

        reverse(result.begin(), result.end());
        return result;
    }
};

Python Code

class Solution:
    def makeGood(self, s: str) -> str:
        stack = []
        for ch in s:
            if stack and abs(ord(ch) - ord(stack[-1])) == 32:
                stack.pop()
            else:
                stack.append(ch)
        
        return ''.join(stack)
        

Javascript Code

/**
 * @param {string} s
 * @return {string}
 */
var makeGood = function(s) {
    const stack = [];
    for (const ch of s) {
        if (stack.length > 0 && Math.abs(stack[stack.length - 1].charCodeAt(0) - ch.charCodeAt(0)) === 32){
            stack.pop();
        } else {
            stack.push(ch);
        }
    }
    return stack.join('');
};

Go Code

func makeGood(s string) string {
    stack := []rune{}
	for _, ch := range s {
		if len(stack) > 0 && abs(int(stack[len(stack)-1])-int(ch)) == 32 {
			stack = stack[:len(stack)-1]
		} else {
			stack = append(stack, ch)
		}
	}
	return string(stack)
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

Time Complexity: O(n)
Space Complexity: O(n)