You are given a string s that consists of lower case English letters and brackets.
Reverse the strings in each pair of matching parentheses, starting from the innermost one.
Your result should not contain any brackets.
Example 1:
Input: s = "(abcd)" Output: "dcba"
Example 2:
Input: s = "(u(love)i)" Output: "iloveu" Explanation: The substring "love" is reversed first, then the whole string is reversed.
Example 3:
Input: s = "(ed(et(oc))el)" Output: "leetcode" Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string.
Constraints:
1 <= s.length <= 2000s only contains lower case English characters and parentheses.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach to reversing substrings within parentheses involves repeatedly finding the innermost set of parentheses, reversing the substring within, and removing those parentheses. We keep doing this until no parentheses remain, resulting in the final reversed string. Think of it like peeling an onion, layer by layer.
Here's how the algorithm would work step-by-step:
def reverse_substrings_brute_force(input_string):
while '(' in input_string:
# Find the innermost parentheses
start_index = -1
end_index = -1
max_start_index = -1
for index, char in enumerate(input_string):
if char == '(':
max_start_index = index
elif char == ')':
start_index = max_start_index
end_index = index
#We found the innermost pair. Break the loop.
break
# Extract the substring to be reversed
substring_to_reverse = input_string[start_index + 1:end_index]
# Reverse the substring
reversed_substring = substring_to_reverse[::-1]
# Replace the parentheses and substring with the reversed substring
input_string = input_string[:start_index] + reversed_substring + input_string[end_index + 1:]
# Continue until no parentheses are left
return input_stringThe trick to efficiently reversing the substrings is to realize that the order of operations is defined by the parentheses. We can use a tool that keeps track of the 'depth' of parentheses and reverses the string at each level when we encounter the closing parenthesis.
Here's how the algorithm would work step-by-step:
def reverse_parentheses(input_string):
stack = ['']
for character in input_string:
if character == '(':
# Start a new string for content inside parentheses.
stack.append('')
elif character == ')':
# Reverse the string inside parentheses.
reversed_substring = stack.pop()[::-1]
stack[-1] += reversed_substring
else:
stack[-1] += character
return stack[0]| Case | How to Handle |
|---|---|
| Empty input string | Return an empty string since there's nothing to reverse. |
| Input string with no parentheses | Return the original string as there are no substrings to reverse. |
| Input string with only one set of parentheses '()' | Reverse the empty string between the parentheses, resulting in empty string which is then removed from final string. |
| Nested parentheses ' (a(bc)d) ' | The solution should correctly handle nested parentheses by reversing from the innermost to the outermost. |
| Adjacent parentheses ' (ab)(cd) ' | The solution should handle multiple sets of independent parentheses correctly, reversing each substring within separately. |
| Input string with a large number of nested parentheses to test recursion depth or stack overflow. | The solution, if recursive, should be optimized or converted to an iterative approach to handle deep nesting without stack overflow issues, or document the known limitations. |
| Input string with a large number of characters within parentheses to test performance. | The string reversal operation should be efficient, ideally using a StringBuilder or similar data structure to avoid excessive string concatenation. |
| Input string with unbalanced parentheses (invalid input). | The problem states the input will be well-formed, but handling invalid inputs gracefully with an exception or error message is good practice to prevent unexpected behavior. |