-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluate_reverse_polish_notation_test.dart
80 lines (66 loc) · 1.83 KB
/
evaluate_reverse_polish_notation_test.dart
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import 'dart:collection';
import 'package:test/test.dart';
// https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/2559166/dart-solution-with-a-stack
/// Evaluate the value of an arithmetic expression in Reverse Polish Notation.
///
/// Valid operators are +, -, *, and /. Each operand may be an integer or another expression.
///
/// Note that division between two integers should truncate toward zero.
///
/// It is guaranteed that the given RPN expression is always valid.
/// That means the expression would always evaluate to a result,
/// and there will not be any division by zero operation.
int evaluateReversePolishNotation(List<String> values) {
final Queue<int> stack = DoubleLinkedQueue();
for (final v in values) {
final op = v.operation;
stack.push(op == null ? int.parse(v) : op(stack.pop(), stack.pop()));
}
return stack.pop();
}
typedef Operation = int Function(int a, int b);
int sum(int a, int b) => b + a;
int subtract(int a, int b) => b - a;
int multiply(int a, int b) => b * a;
int divide(int a, int b) => b ~/ a;
extension on String {
Operation? get operation =>
const {'+': sum, '-': subtract, '*': multiply, '/': divide}[this];
}
extension MinimalistStack<E> on Queue<E> {
void push(E value) => addLast(value);
E pop() => removeLast();
}
void main() {
test('leetcode', () {
expect(13 ~/ 5, 2);
expect(
evaluateReversePolishNotation(['2', '1', '+', '3', '*']),
9,
);
expect(
evaluateReversePolishNotation(['4', '13', '5', '/', '+']),
6,
);
expect(
evaluateReversePolishNotation(
[
'10',
'6',
'9',
'3',
'+',
'-11',
'*',
'/',
'*',
'17',
'+',
'5',
'+',
],
),
22,
);
});
}