Swift solution using Stack, easy understanding


  • 0
    func evalRP(tokens: [String]) -> Int {
        
        struct Stack<Element> {
            
            private var container = [Element]()
            
            var topElement: Element? {
                get {
                    return container.last
                }
            }
            
            mutating func push(element: Element) {
                container.append(element)
            }
            
            mutating func pop() -> Element? {
                guard container.count != 0 else { return nil }
                return container.removeLast()
            }
            
            func isEmpty() -> Bool {
                return container.count == 0
            }
        }
        
        
        
        enum Operator: String {
            case Add = "+"
            case Subtract = "-"
            case Multiply = "*"
            case Divide = "/"
        }
        
        var stack = Stack<Int>()
        
        for element in tokens {
            // if it's an operator
            if let op = Operator(rawValue: element) {
                let rightNumber = stack.pop()
                if rightNumber == nil {
                    continue
                }
                
                let leftNumber = stack.pop()
                if leftNumber == nil {
                    stack.push(rightNumber!)
                    continue
                }
                
                var result = 0
                switch op {
                case .Add:
                    result = leftNumber! + rightNumber!
                case .Subtract:
                    result = leftNumber! - rightNumber!
                case .Divide:
                    result = leftNumber! / rightNumber!
                case .Multiply:
                    result = leftNumber! * rightNumber!
                }
                stack.push(result)
                
            } else {
                if let number = Int(element) {
                    stack.push(number)
                } else {
                    // input type error
                    return 0;
                }
            }
        }
        
        return stack.topElement ?? 0   
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.