給你一個(gè)字符串表達(dá)式 s ,請(qǐng)你實(shí)現(xiàn)一個(gè)基本計(jì)算器來計(jì)算并返回它的值。
整數(shù)除法僅保留整數(shù)部分。
- 1 <= s.length <= 3 * 105
- s 由整數(shù)和算符 '+', '-', '*', '/' 組成,中間由一些空格隔開
- s 表示一個(gè) 有效表達(dá)式
- 表達(dá)式中的所有整數(shù)都是非負(fù)整數(shù),且在范圍 [0, 231 - 1] 內(nèi)
- 題目數(shù)據(jù)保證答案是一個(gè) 32-bit 整數(shù)
例子:
輸入:s = "3+2*2"
輸出:7
輸入:s = " 3/2 "
輸出:1
輸入:s = " 3+5 / 2 "
輸出:5
解題思路:
棧方法
跟IOS 算法(困難篇) ----- 基本計(jì)算器類似, 依舊使用棧方法進(jìn)行處理
數(shù)字進(jìn)入棧
乘除將計(jì)算完數(shù)字進(jìn)入棧
最后計(jì)算棧中元素之和
代碼:
未翻譯版
var ops = [String](), num = ""
func calculate(_ s: String) -> Int {
let temp = s.replacingOccurrences(of: " ", with: "")
for i in temp {
if i == "+" {
cal()
}else if i == "-" {
cal()
num += "-"
}else if i == "*" {
cal()
ops.append("*")
}else if i == "/" {
cal()
ops.append("/")
}else {
num += String(i)
}
}
cal()
var result = 0
for i in ops {
result += Int(i) ?? 0
}
return result
}
func cal() {
if ops.last == "*" {
ops.removeLast()
let mul1 = Int(ops.removeLast()) ?? 0, mul2 = Int(num) ?? 0
num = String(mul1 * mul2)
}else if ops.last == "/" {
ops.removeLast()
let div1 = Int(ops.removeLast()) ?? 0, div2 = Int(num) ?? 0
num = String(div1 / div2)
}
ops.append(num)
num = ""
}
翻譯版
// 定義棧數(shù)組, num為數(shù)字容器
var ops = [String](), num = ""
func calculate(_ s: String) -> Int {
// temp為s去空格之后字符串
let temp = s.replacingOccurrences(of: " ", with: "")
// 循環(huán)
for i in temp {
if i == "+" {
// 數(shù)字入棧
cal()
}else if i == "-" {
// 數(shù)字入棧, num初始置為負(fù)"-"
cal()
num += "-"
}else if i == "*" {
// 數(shù)字入棧, 乘法多拼接 "*"
cal()
ops.append("*")
}else if i == "/" {
// 數(shù)字入棧, 乘法多拼接 "/"
cal()
ops.append("/")
}else {
// 普通情況數(shù)字拼接
num += String(i)
}
}
// 最后剩余數(shù)字入棧
cal()
// 計(jì)算棧中元素和即最后結(jié)果
var result = 0
for i in ops {
result += Int(i) ?? 0
}
//返回結(jié)果
return result
}
// 公共方法 ops棧中添加數(shù)字
func cal() {
if ops.last == "*" {
// 如果末尾是 * , 先計(jì)算乘法之后再入棧
// 移出" * "
ops.removeLast()
// 和之前元素做乘法
let mul1 = Int(ops.removeLast()) ?? 0, mul2 = Int(num) ?? 0
num = String(mul1 * mul2)
}else if ops.last == "/" {
// 如果是 / 先計(jì)算除法之后再入棧
// 移出" / "
ops.removeLast()
// 和之前元素做除法
let div1 = Int(ops.removeLast()) ?? 0, div2 = Int(num) ?? 0
num = String(div1 / div2)
}
// 數(shù)字入棧, 之后num至空字符串
ops.append(num)
num = ""
}
題目來源:力扣(LeetCode) 感謝力扣爸爸 :)
IOS 算法合集地址