λ¬Έμ :
https://programmers.co.kr/learn/courses/30/lessons/67257?language=swift
λμ΄λ : level2
λΆμ :
*, -, + 3κ°μ μ°μ°μλ₯Ό κ°μ§κ³ μμμ μ΅λν νλ μ°μ°μμ μ°μ μμλ₯Ό μ μ©ν΄ μ΅λκ°μ 리ν΄νλ λ¬Έμ λ€.
λλ μμμ΄ 3κ°λ°μ μμ΄μ (3! => 6) κ°λ₯ν κ²½μ°μ μλ₯Ό μμ½λ©νμλ€.
κ·Έλ¦¬κ³ μ°μ°μκ° λ±μ₯νλ μμλλ‘ opλ°°μ΄μ λ΄μκ³
κ°λ₯ν μ°μ μμλ₯Ό λͺ¨λ κ³μ°ν΄ resultλ°°μ΄μμ κ³μ°ν κ°μ μμ νκ³ κ³μ°νμ¬ μμκ° νκ° λ¨μμ κ²½μ° μ΅λκ°μ μ λ°μ΄νΈ ν΄μ£Όμλ€.
Swift μ½λ :
//
// main.swift
// SOMAπ©π»π»
//
// Created by JoSoJeong on 2022/04/14.
//
import Foundation
func calc(_ n1: Int64, _ n2: Int64, _ op: String) -> Int64 {
switch op {
case "+":
return n1 + n2
case "*":
return n1 * n2
case "-":
return n1 - n2
default:
return 0
}
}
func solution(_ expression:String) -> Int64 {
let priority: [[String]] = [["*", "+", "-"], ["*", "-", "+"], ["+", "*", "-"], ["+", "-", "*"], ["-", "+", "*"], ["-", "*", "+"]]
var str = expression
var arr = str.components(separatedBy: ["-", "*", "+"]).map { Int64(String($0))! }
var op: [String] = []
//op μμλλ‘ κ³μ°
for i in str {
if i == "-" {
op.append("-")
}else if i == "*" {
op.append("*")
}else if i == "+" {
op.append("+")
}
}
var answer:Int64 = 0
for i in priority {
var now = i
var result = arr
var nowOp = op
for ii in now {
while nowOp.contains(ii) {
if let index = nowOp.firstIndex(of: ii) {
result[index] = calc(result[index], result[index+1], ii)
result.remove(at: index+1) // κ³μ°ν μ«μ μ§μ°κΈ°
nowOp.remove(at: index)
}
}
}
if result.count != 1 { continue }
if result.first! < 0 { //μ λκ°
answer = max(answer, -result.first!)
}else {
answer = max(answer, result.first!)
}
}
return answer
}
μ€ν κ²°κ³Ό :
λκΈ