Reverse and Simplify String
Given an expression string, such as AB(D)D((AS))B
and a formula string containing R's and S's, such as RSRRSRSSR
, perform the operations in the formula string onto the expression string. The commands of the formula string represent the following:
Full Example
The Idea: Reverse is a simple string reversal with the parenthesis flipped to their matching pair. Simplify is more complex. What I did is identify matching parenthesis pairs, then grouped them based of their adjacency to each other. A pair of parenthesis will belong to group i
when it's minimum distance to one pair within the group is one. Simplification then just means iterating through these groups and removing 1 pair from each if there are two or more pairs within the group.
Complexity: O(n^2logn)
, where n is the length of formula string -> O(n+n)
for single reversal and, O(n+nlogn+n+n)
for simplification. O(n)
space.
Improvements: Since RR = null
and RRR = R
modify the formula string to have 0 to 1 consecutive Rs based on identification of an odd or even number of Rs. Secondly, rather than recalculating the positions and groups of parenthesis every time, perform it once, and then on a reversal - reverse the positions of the parenthesis. Lastly, initiate a flag when there are no more redundant parenthesis groups - and skip remaining S calculations.
Last updated