3612. Process String with Special Operations I
- String
- Simulation
- Stack
TIME
O(n * L)
SPACE
O(L)
Intuition
There is no hidden structure, each character is a direct instruction on the running buffer. Just carry out the operations in order. Since s has at most 20 characters (and only the few # before the final state can grow it), the buffer stays small, so a plain simulation is more than fast enough.
Approach
Maintain result as a mutable list of characters and process each character of s:
- Lowercase letter -> append it.
'*'-> pop the last character if the buffer is non-empty.'#'-> double the buffer (result += result).'%'-> reverse the buffer in place.
Join the list into a string at the end.
Complexity
- Time: O(n * L), for each of the
ncharacters, an op may touch up to the current lengthL(reverse/duplicate); bounded and tiny here - Space: O(L), the result buffer
Edge Cases
'*'on an empty buffer -> no-op'#'on an empty buffer -> stays empty'%'on an empty or single-character buffer -> unchanged- A string of only special characters -> result can end up empty
Code
class Solution:
def processStr(self, s: str) -> str:
"""
3612. Process String with Special Operations I
Time: O(n * L)
Space: O(L)
"""
result = []
for ch in s:
if ch == "*":
if result:
result.pop()
elif ch == "#":
result += result
elif ch == "%":
result.reverse()
else:
result.append(ch)
return "".join(result)/**
* 3612. Process String with Special Operations I
* Time: O(n * L)
* Space: O(L)
*/
class Solution {
public String processStr(String s) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '*') {
if (result.length() > 0) {
result.deleteCharAt(result.length() - 1);
}
} else if (ch == '#') {
result.append(result);
} else if (ch == '%') {
result.reverse();
} else {
result.append(ch);
}
}
return result.toString();
}
}