★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10204363.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

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 }

转载于:https://www.cnblogs.com/strengthen/p/10204363.html

[Swift]LeetCode227. 基本计算器 II | Basic Calculator II相关推荐

  1. LeetCode OJ Basic Calculator II

    Basic Calculator II 题目 思路 和这个一样:Basic Calculator I 代码 class ExpressionTransformation { public:string ...

  2. 【LeetCode】Basic Calculator II

    Basic Calculator II 问题描述 Implement a basic calculator to evaluate a simple expression string. The ex ...

  3. LeetCode Basic Calculator II(加减乘除计算器)

    与 LeetCode Basic Calculator(用栈计算表达式的值)相似 代码如下: public class Solution {private int cal(int num1, int ...

  4. 227. Basic Calculator II

    The expression string contains only non-negative integers, +, -, *, / operators and empty spaces. Th ...

  5. Basic Calculator II

    该题和前面的" Basic Calculator "的处理方法一样,仅仅是增加了对"*"."/"两种运算的支持. class Solutio ...

  6. 227 Basic Calculator II

    1 题目 Implement a basic calculator to evaluate a simple expression string.The expression string conta ...

  7. leetcode----227. Basic Calculator II

    链接: https://leetcode.com/problems/basic-calculator-ii/ 大意: 实现一个计算器.给定一个字符串s,字符串s中的字符由'0'-'9'的数字以及'+' ...

  8. leetcode 227. Basic Calculator II | 227. 基本计算器 II(中缀表达式求值)

    题目 https://leetcode.com/problems/basic-calculator-ii/ 题解 这道题是 中缀表达式求值 的简化版(因为没有左右括号运算),不过输入的形式有两个处理起 ...

  9. Basic Calculator 基本计算器-Leetcode

    1.题目: Implement a basic calculator to evaluate a simple expression string. The expression string may ...

最新文章

  1. java源文件到字节码的命令,Java的源代码文件的扩展名是 ,Java源文件通过编译命令编译成的字节码文件(平台无关)的扩展名是 。...
  2. Android 游戏开发入门
  3. JS数据类型及函数的预编译
  4. mysql的各种语句_MySql常用操作SQL语句汇总
  5. 第二章:Webdriver 控制浏览器前进和后退
  6. 求离散数据的突变点_Nat Gen | 染色质三维构象决定突变分布
  7. linux添加window启动
  8. 【AI视野·今日Robot 机器人论文速览 第八期】Wed, 16 Jun 2021
  9. java 输出字符串的所有排列_JAVA 输出指定字符串所有排列组合
  10. 基于mysql的分析型数据库_数据仓库_数据分析_分析型数据库_MySQL查询
  11. 分享一款实用的APP开发框架
  12. java实现思维导图_Java并发(思维导图)
  13. wow私服,arcemu trunk源码编译架设
  14. 新旧骗术揭秘:防止5G时代的电信诈骗
  15. 图片裁剪工具vue-img-cutter
  16. QtCreator添加文件夹
  17. 微信开发网页授权认证
  18. nginx的安装(亲测)
  19. java中的LinkedList(链表)与ArrayList(动态数组):(2)尝试简单实现LinkedList
  20. 计算机网络cdm名词解释,计算机网络_名词解释

热门文章

  1. linux 设备驱动阻塞,深入浅出:Linux设备驱动中的阻塞和非阻塞I/O
  2. es文件浏览器怎么用_ES文件浏览器——安卓第一文件管理APP
  3. Python高级专题 - 类型转换的魔术方法
  4. 2018年php框架,2018年的7个热门网站开发框架
  5. 集合字典序(优先队列)
  6. HDU 1698 Just a Hook (线段树区间修改+区间查询)
  7. mysql数据库用doc命令,myMySQL数据库怎么使用dos命令安装? MySQL数据库使用教程
  8. [Pro]斐波那契数列阿【斐波那契数列】
  9. 分布式系统关注点——如何去实施「负载均衡」?
  10. Codeforces 86C Genetic engineering (AC自己主动机+dp)