Skip to content

Commit ac531e9

Browse files
committed
[Stack] Optimize code style of solution to Evaluate Reverse Polish Notation
1 parent e0bc990 commit ac531e9

File tree

1 file changed

+7
-20
lines changed

1 file changed

+7
-20
lines changed

Stack/EvaluateReversePolishNotation.swift

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,37 +5,24 @@
55
*/
66

77
class EvaluateReversePolishNotation {
8-
func evalRPN(tokens: [String]) -> Int {
8+
func evalRPN(_ tokens: [String]) -> Int {
99
var stack = [Int]()
1010

11-
for str in tokens {
12-
if _isNumber(str) {
13-
stack.append(Int(str)!)
11+
for token in tokens {
12+
if let num = Int(token) {
13+
stack.append(num)
1414
} else {
15-
guard stack.count > 1 else {
16-
return 0
17-
}
18-
1915
let post = stack.removeLast()
2016
let prev = stack.removeLast()
2117

22-
let res = _operate(prev, post, str)
23-
stack.append(res)
18+
stack.append(operate(prev, post, token))
2419
}
2520
}
2621

27-
if stack.count == 0 {
28-
return 0
29-
} else {
30-
return stack.first!
31-
}
32-
}
33-
34-
private func _isNumber(str: String) -> Bool {
35-
return Int(str) != nil
22+
return stack.first ?? 0
3623
}
3724

38-
private func _operate(prev: Int, _ post: Int, _ token: String) -> Int{
25+
fileprivate func _operate(_ prev: Int, _ post: Int, _ token: String) -> Int{
3926
switch token {
4027
case "+":
4128
return prev + post

0 commit comments

Comments
 (0)