LeetCode每日一题(2232. Minimize Result by Adding Parentheses to Expression)

给定形如 '数字+数字' 的字符串表达式,你需要在加号两侧添加一对括号,使得表达式合法且计算结果最小。返回能使表达式值最小的添加括号后的字符串。输入确保原始值及括号添加后的值都在32位整数范围内。
摘要由CSDN通过智能技术生成

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.

Constraints:

  • 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.

用/和%操作把数字拆分, 然后找最小组合, 注意/1 和%1 的特殊情况处理


impl Solution {
   
    pub fn minimize_result(expression: String) -> String {
   
        let tokens: Vec<&
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值