leetcode 2232. Minimize Result by Adding Parentheses to Expression(python)

Get into the habit of writing together! This is the 13th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the event details .

describe

You are given a 0-indexed string expression of the form "+" where and represent positive integers.

Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'.

Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them.

The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.

Example 1:

Input: expression = "247+38"
Output: "2(47+38)"
Explanation: The expression evaluates to 2 * (47 + 38) = 2 * 85 = 170.
Note that "2(4)7+38" is invalid because the right parenthesis must be to the right of the '+'.
It can be shown that 170 is the smallest possible value.
复制代码

Example 2:

Input: expression = "12+34"
Output: "1(2+3)4"
Explanation: The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20.
复制代码

Example 3:

Input: expression = "999+999"
Output: "(999+999)"
Explanation: The expression evaluates to 999 + 999 = 1998.
复制代码

Note:

3 <= expression.length <= 10
expression consists of digits from '1' to '9' and '+'.
expression starts and ends with digits.
expression contains exactly one '+'.
The original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
复制代码

Parse

According to the meaning of the question, given a 0-indexed string expression of the form "+", where sum represents a positive integer.

After adding a pair of parentheses to the expression, the expression is a valid mathematical expression. In fact, the addition operation is performed inside the parentheses, and the multiplication operation is performed outside the parentheses, requiring us to calculate the string corresponding to the smallest possible result value. If you don't understand, look at the examples given to understand.

Since there can be a bunch of parentheses in various places, if there are multiple answers, any one of them is returned.

In fact, this question examines the understanding of the question and the violent solution. I used violence to solve it during the competition, because the maximum length of expression in the constraints is 10, and the violent solution can save a lot of thinking during the competition. time, the same can be AC. But after the game, I went to the forum to find a simpler solution, and found that the violent solution [cover face] was used, which also lost the motivation to optimize the code.

My idea is actually very simple, although the code is a bit long, but it is easy to understand:

  • Extract the two numbers in expression to be A or B respectively
  • Use two variables i and j to represent the position of the left bracket at A and the position of the right bracket at B, and perform a double loop traversal
  • Because "(" can cut A into two parts, preA and tailA (of course, if preA is empty, because its position needs to be multiplied, it must be assigned a value of 1; if tailA is empty, because its position needs to be added, it needs to be Assign it to 0); ")" can cut B into two parts preB and tailB (for the empty case, the same as the above processing method)
  • Calculate preA*(tailA + preB)*tailB, if it is less than the current mx, update the final result string result
  • At the end of the loop, return directly to result

N1 and N2 are the string lengths of two numbers respectively, the time complexity is O(N1 * N2), and the space complexity is O(N1 + N2).

answer

class Solution(object):
    def minimizeResult(self, expression):
        """
        :type expression: str
        :rtype: str
        """
        A,B = expression.split('+')
        n1 = len(A)
        n2 = len(B)
        mx = float('inf')
        result = ''
        for i in range(n1):
            preA = A[:i]
            if not preA:
                preA = 1
            tailA = A[i:]
            if not tailA:
                tailA = 0
            for j in range(1, n2+1):
                preB = B[:j]
                if not preB:
                    preB = 0
                tailB = B[j:]
                if not tailB:
                    tailB = 1
                tmp = int(preA)*(int(tailA) + int(preB))*int(tailB)
                if mx > tmp:
                    mx = min(mx, tmp)
                    result  = A[:i] + '(' + A[i:] + '+' + B[:j] + ')' + B[j:]
        return result		
复制代码

operation result

124 / 124 test cases passed.
Status: Accepted
Runtime: 34 ms
Memory Usage: 13.6 MB
复制代码

Original title link

leetcode.com/contest/wee…

Your support is my greatest motivation

Guess you like

Origin juejin.im/post/7085887146233430047