#3612

Process String with Special Operations I

Medium
StringSimulationStackString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

This approach uses a stack to efficiently manage the result string, allowing for quick operations without excessive string manipulation.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty stack.
  2. 2Step 2: Iterate through each character in the input string.
  3. 3Step 3: For letters, push to stack; for '*', pop; for '#', duplicate the stack; for '%', reverse the stack.
solution.py12 lines
1def process_string(s):
2    stack = []
3    for char in s:
4        if char.isalpha():
5            stack.append(char)
6        elif char == '*':
7            if stack: stack.pop()
8        elif char == '#':
9            stack += stack
10        elif char == '%':
11            stack.reverse()
12    return ''.join(stack)

Complexity note: The stack allows for efficient operations, maintaining a linear time complexity as each operation is handled in constant time.

  • 1Stack usage simplifies operations
  • 2In-place operations reduce time complexity

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.