52 lines
1.2 KiB
Swift
52 lines
1.2 KiB
Swift
func opPriority(_ op: Character) -> Int {
|
|
return (op == "*") || (op == "/") ? 2 : (op == "+") || (op == "-") ? 1 : 0
|
|
}
|
|
|
|
func compareToPriority(_ op1: Character, _ op2: Character) -> Bool {
|
|
return opPriority(op1) >= opPriority(op2)
|
|
}
|
|
|
|
if let input = readLine() {
|
|
var result: String = ""
|
|
var op: [Character] = []
|
|
|
|
for c in input {
|
|
if "A" <= c && c <= "Z" {
|
|
result.append(c)
|
|
}
|
|
else {
|
|
if c == "(" {
|
|
op.append(c)
|
|
}
|
|
else if c == ")" {
|
|
while !op.isEmpty && op.last != "(" {
|
|
if let top = op.popLast() {
|
|
result.append(top)
|
|
}
|
|
}
|
|
|
|
if !op.isEmpty {
|
|
_ = op.popLast()
|
|
}
|
|
}
|
|
else {
|
|
while !op.isEmpty && compareToPriority(op.last!, c) {
|
|
if let top = op.popLast() {
|
|
result.append(top)
|
|
}
|
|
}
|
|
|
|
op.append(c)
|
|
}
|
|
}
|
|
}
|
|
|
|
while !op.isEmpty {
|
|
if let top = op.popLast() {
|
|
result.append(top)
|
|
}
|
|
}
|
|
|
|
print(result)
|
|
}
|