Similar Problems
Similar Problems not available
Evaluate The Bracket Pairs Of A String - Leetcode Solution
Companies:
LeetCode: Evaluate The Bracket Pairs Of A String Leetcode Solution
Difficulty: Medium
Topics: string hash-table array
Problem Statement: You are given a string s that contains some bracket pairs, represented by the characters '(' and ')'. Each bracket pair represents a dependency, where the content inside the parentheses must be evaluated before the content outside. The content inside the parentheses will only contain lowercase letters, and the content outside the parentheses will only contain uppercase letters.
You need to evaluate the string and return it with all the bracket pairs evaluated first.
Example:
Input: s = "(a)(b)" Output: "ab"
Input: s = "(a(b(c)d))" Output: "abcd"
Solution:
The problem is asking us to evaluate the bracket pairs of a string. We will solve this problem using stack data structure.
Algorithm:
-
Create a stack to store all the characters while traversing the string from left to right.
-
While traversing the string, if encounters an opening bracket of '(' of a pair, we will push it into the stack.
-
If we encounter a closing bracket ')', then pop the characters from the stack until we reach the opening bracket '('.
-
If we find any character between the opening and closing brackets, we will append it to the result.
-
Once we have evaluated all the bracket pairs, append all the remaining characters of the stack to the result.
-
Return the final result.
Code in Python:
class Solution: def evaluate(self, s: str) -> str: stack = [] result = ""
for char in s:
if char == ')':
tmp = ""
while stack[-1] != '(':
tmp = stack.pop() + tmp
stack.pop()
if tmp:
stack.append(tmp)
else:
stack.append(char)
while stack:
result = stack.pop() + result
return result
Complexity Analysis:
Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(n), where n is the length of the input string. The stack can have at most all the characters of the input string, resulting in space complexity of O(n).
Evaluate The Bracket Pairs Of A String Solution Code
1