Skip to content

Commit

Permalink
[Stack] add solution to Evaluate Reverse Polish Notation and Valid Pa…
Browse files Browse the repository at this point in the history
…rentheses
  • Loading branch information
Yi Gu committed May 19, 2016
1 parent 75513f1 commit 6557bf1
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
50 changes: 50 additions & 0 deletions Stack/EvaluateReversePolishNotation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Question Link: https://leetcode.com/problems/evaluate-reverse-polish-notation/
* Primary idea: Push a number to a stack and pop two for operation when encounters a operator
* Time Complexity: O(n), Space Complexity: O(n)
*/

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

for str in tokens {
if _isNumber(str) {
stack.append(Int(str)!)
} 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)
}
}

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

private func _isNumber(str: String) -> Bool {
return Int(str) != nil
}

private func _operate(prev: Int, _ post: Int, _ token: String) -> Int{
switch token {
case "+":
return prev + post
case "-":
return prev - post
case "*":
return prev * post
default:
return prev / post
}
}
}
31 changes: 31 additions & 0 deletions Stack/ValidParentheses.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* Question Link: https://leetcode.com/problems/valid-parentheses/
* Primary idea: Use a stack to see whether the peek left brace is correspond to the current right one
* Time Complexity: O(n), Space Complexity: O(n)
*/

class ValidParentheses {
func isValid(s: String) -> Bool {
var stack = [Character]()

for char in s.characters {
if char == "(" || char == "[" || char == "{" {
stack.append(char)
} else if char == ")" {
guard stack.count != 0 && stack.removeLast() == "(" else {
return false
}
} else if char == "]" {
guard stack.count != 0 && stack.removeLast() == "[" else {
return false
}
} else if char == "}" {
guard stack.count != 0 && stack.removeLast() == "{" else {
return false
}
}
}

return stack.count == 0
}
}

0 comments on commit 6557bf1

Please sign in to comment.