1. 程式人生 > >[Swift]LeetCode227. 基本計算器 II | Basic Calculator II

[Swift]LeetCode227. 基本計算器 II | Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +-*/operators and empty spaces . The integer division should truncate toward zero.

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

Note:

  • You may assume that the given expression is always valid.
  • Do not use the eval built-in library function.

實現一個基本的計算器來計算一個簡單的字串表示式的值。

字串表示式僅包含非負整數,+, - ,*/ 四種運算子和空格  。 整數除法僅保留整數部分。

示例 1:

輸入: "3+2*2"
輸出: 7

示例 2:

輸入: " 3/2 "
輸出: 1

示例 3:

輸入: " 3+5 / 2 "
輸出: 5

說明:

  • 你可以假設所給定的表示式都是有效的。
  • 請不要使用內建的庫函式 eval

116ms

 1 class Solution {
 2     func calculate(_ s: String) -> Int {
 3         var num = 0
 4         var sign = "+"
 5         var strArr = Array(s)
6 var stack = [Int]() 7 var res = 0 8 9 for i in 0..<strArr.count { 10 if strArr[i] >= "0" && strArr[i] <= "9" { 11 num = num * 10 + Int(String(strArr[i]))! 12 } 13 14 if ((strArr[i] < "0" || strArr[i] > "9") && strArr[i] != " ") || i == strArr.count - 1 { 15 if sign == "+" { 16 stack.append(num) 17 } else if sign == "-" { 18 stack.append(-num) 19 } else if sign == "*" { 20 stack.append(stack.removeLast() * num) 21 } else if sign == "/" { 22 stack.append(stack.removeLast() / num) 23 } 24 25 sign = String(strArr[i]) 26 num = 0 27 } 28 } 29 30 31 for i in stack { 32 res += i 33 } 34 35 return res 36 } 37 }

124ms

 1 class Solution {
 2     func calculate(_ s: String) -> Int {
 3         var stack = [Int]()
 4         var str = Array(s+"+")
 5         
 6         var num = 0
 7         var sign: Character = "+"
 8         
 9         for char in str {
10             if char >= "0" && char <= "9" {
11                 num = num * 10 + Int(String(char))!
12             } else if operators.contains(char) {
13                 if sign == "+" || sign == "-"{
14                     stack.append((sign == "-" ? -1 : 1) * num)
15                 } else if sign == "*" || sign == "/" {
16                     let n = stack.removeLast()
17                     stack.append(sign == "*" ? n * num : n / num)
18                 }
19                 num = 0
20                 sign = char
21             }
22         }
23         return stack.reduce(0, +)
24     }
25     
26     let operators = Set<Character>(["+", "-", "*", "/"])
27 }

140ms

 1 class Solution {
 2     func calculate(_ s: String) -> Int {
 3         var stack = [Int]()
 4         var str = Array(s+"+")
 5         
 6         var num = 0
 7         var sign: Character = "+"
 8         
 9         for char in str {
10             if operands.contains(char) {
11                 num = num * 10 + Int(String(char))!
12             } else if operators.contains(char) {
13                 if sign == "+" || sign == "-"{
14                     stack.append((sign == "-" ? -1 : 1) * num)
15                 } else if sign == "*" || sign == "/" {
16                     let n = stack.removeLast()
17                     stack.append(sign == "*" ? n * num : n / num)
18                 }
19                 num = 0
20                 sign = char
21             }
22         }
23         return stack.reduce(0, +)
24     }
25     
26     let operators = Set<Character>(["+", "-", "*", "/"])
27     let operands = Set<Character>(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"])
28 }

228ms

 1 class Solution {
 2     func calculate(_ s: String) -> Int {
 3         var nums: [Int] = []
 4         var operations: [Character] = []
 5         var preNum = ""
 6         for char in s {
 7             if let _ = Int(String(char)) {
 8                 preNum += String(char)
 9             } else {
10                 if preNum != "" {
11                     nums.append(Int(preNum)!)
12                     preNum = ""
13                 }
14 
15                 if !operations.isEmpty {
16                     let operation = operations[operations.count - 1]
17                     if nums.count > operations.count && (operation == "*" || operation == "/") {
18                         let num2 = nums.popLast()!
19                         let num1 = nums.popLast()!
20                         if operation == "*" {
21                             let num = num1 * num2
22                             nums.append(num)
23                         } else if operation == "/" {
24                             let num = num1 / num2
25                             nums.append(num)
26                         }
27 
28                         operations.removeLast()
29                     }
30                 }
31 
32 
33                 if char != " " {
34                     operations.append(char)
35                 }
36             }
37         }
38 
39         if preNum != "" {
40             nums.append(Int(preNum)!)
41         }
42 
43         if !operations.isEmpty && operations.last == "/" || operations.last == "*" {
44             let operation = operations.popLast()!
45             let num2 = nums.popLast()!
46             let num1 = nums.popLast()!
47             if operation == "*" {
48                 nums.append(num1 * num2)
49             } else if operation == "/" {
50                 nums.append(num1 / num2)
51             }
52         }
53     
54         nums.reverse()
55         for operation in operations {
56             let num1 = nums.popLast()!
57             let num2 = nums.popLast()!
58             if operation == "+" {
59                 nums.append(num1 + num2)
60             } else if operation == "-" {
61                 nums.append(num1 - num2)
62             } else if operation == "*" {
63                 nums.append(num1 * num2)
64             } else if operation == "/" {
65                 nums.append(num1 / num2)
66             }
67         }
68 
69         return nums.isEmpty ? 0 : nums[0]
70     }
71 }

548ms

 1 class Solution {
 2     func calculate(_ s: String) -> Int {
 3         var numStack = [Int]()
 4         var opeStack = [String]()
 5         let sArr = Array(s)
 6         let nums = "0123456789"
 7         let opes = "+-*/"
 8         
 9         var i = 0
10         while i < sArr.count {
11             let c = sArr[i]
12             if nums.contains(c) {
13                 var tmp = 0
14                 while i < sArr.count && nums.contains(sArr[i]) {
15                     tmp = tmp * 10 + Int(String(sArr[i]))!
16                     i += 1
17                 }
18                 if let ope = opeStack.last, ope == "*" || ope ==  "/" {
19                     let last = numStack.removeLast()
20                     opeStack.removeLast()
21                     if ope == "*" {
22                         tmp *= last
23                     }else if ope == "/" {
24                         tmp = last / tmp
25                     }
26                     
27                 }
28                 numStack.append(tmp)
29                 i -= 1
30             }else if opes.contains(c) {
31                 opeStack.append(String(c))
32             }
33             
34             i += 1
35         }
36         
37         var res = numStack.first ?? 0
38         
39         for i in 0..<opeStack.count {
40             let ope = opeStack[i]
41             if ope == "+" {
42                 res += numStack[i+1]
43             }else if ope == "-" {
44                 res -= numStack[i+1]
45             }
46         }
47         return res
48     }
49 }