Make The String Great — LeetCode 1544 Python Solution
- Problem
- #1544
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- s = "leEeetcode"
- Output
- "leetcode"
- Explanation
- In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".
Python solution
class Solution:
def makeGood(self, s: str) -> str:
stk = []
for c in s:
if not stk or abs(ord(stk[-1]) - ord(c)) != 32:
stk.append(c)
else:
stk.pop()
return "".join(stk)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1544. Make The String Great is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1544. Make The String Great?
- LeetCode 1544. Make The String Great is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1544. Make The String Great?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1544. Make The String Great?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1544. Make The String Great cover?
- LeetCode 1544. Make The String Great is tagged Stack and String on LeetCode.