Skip to content

Commit

Permalink
[Stack] Optimize code style of solution to Evaluate Reverse Polish No…
Browse files Browse the repository at this point in the history
…tation
  • Loading branch information
soapyigu committed May 31, 2018
1 parent e0bc990 commit ac531e9
Showing 1 changed file with 7 additions and 20 deletions.
27 changes: 7 additions & 20 deletions Stack/EvaluateReversePolishNotation.swift
Expand Up @@ -5,37 +5,24 @@
*/

class EvaluateReversePolishNotation {
func evalRPN(tokens: [String]) -> Int {
func evalRPN(_ tokens: [String]) -> Int {
var stack = [Int]()

for str in tokens {
if _isNumber(str) {
stack.append(Int(str)!)
for token in tokens {
if let num = Int(token) {
stack.append(num)
} else {
guard stack.count > 1 else {
return 0
}

let post = stack.removeLast()
let prev = stack.removeLast()

let res = _operate(prev, post, str)
stack.append(res)
stack.append(operate(prev, post, token))
}
}

if stack.count == 0 {
return 0
} else {
return stack.first!
}
}

private func _isNumber(str: String) -> Bool {
return Int(str) != nil
return stack.first ?? 0
}

private func _operate(prev: Int, _ post: Int, _ token: String) -> Int{
fileprivate func _operate(_ prev: Int, _ post: Int, _ token: String) -> Int{
switch token {
case "+":
return prev + post
Expand Down

0 comments on commit ac531e9

Please sign in to comment.