-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathminimize-result-by-adding-parentheses-to-expression.rs
66 lines (55 loc) · 1.59 KB
/
minimize-result-by-adding-parentheses-to-expression.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#![allow(dead_code, unused, unused_variables, non_snake_case)]
fn main() {
assert_eq!(
Solution::minimize_result("12+34".to_string()),
"1(2+3)4".to_string()
);
}
struct Solution;
impl Solution {
pub fn minimize_result(expression: String) -> String {
let mut expression = expression.split('+');
let left = expression.next().unwrap();
let right = expression.next().unwrap();
let mut left_index = 0;
let mut right_index = 0;
let mut min = i32::MAX;
for i in 0..left.len() {
let l1 = if i == 0 {
1
} else {
left[..i].parse::<i32>().unwrap()
};
let l2 = if i < left.len() {
left[i..].parse::<i32>().unwrap()
} else {
1
};
for j in 1..=right.len() {
let l3 = if j == 0 {
1
} else {
right[..j].parse::<i32>().unwrap()
};
let l4 = if j < right.len() {
right[j..].parse::<i32>().unwrap()
} else {
1
};
let c = l1 * (l2 + l3) * l4;
if c < min {
left_index = i;
right_index = j;
min = c;
}
}
}
format!(
"{}({}+{}){}",
&left[..left_index],
&left[left_index..],
&right[..right_index],
&right[right_index..]
)
}
}