Skip to content

Adjacent Elimination

Table of Contents

2696. Minimum String Length After Removing Substrings

1047. Remove All Adjacent Duplicates In String

1544. Make The String Great

"""
-   Remove all adjacent characters that are the same and have different cases.
-   Steps for the string `leEeetcode`:

| char | action | stack      |
| ---- | ------ | ---------- |
| l    | push   | "l"        |
| e    | push   | "le"       |
| E    | pop    | "l"        |
| e    | push   | "le"       |
| e    | push   | "lee"      |
| t    | push   | "leet"     |
| c    | push   | "leetc"    |
| o    | push   | "leetco"   |
| d    | push   | "leetcod"  |
| e    | push   | "leetcode" |
"""


# Stack
def makeGood(s: str) -> str:
    stack = []

    for i in range(len(s)):
        if stack and stack[-1] == s[i].swapcase():
            stack.pop()
        else:
            stack.append(s[i])
    return "".join(stack)


print(makeGood("leEeetcode"))  # "leetcode"

1003. Check If Word Is Valid After Substitutions

2216. Minimum Deletions to Make Array Beautiful

1209. Remove All Adjacent Duplicates in String II

2211. Count Collisions on a Road

735. Asteroid Collision

1717. Maximum Score From Removing Substrings

2197. Replace Non-Coprime Numbers in Array

2751. Robot Collisions

Comments