정규식을 사용하여 해결할 수 있습니다

 

 

 

정규식이란 "[+-]" 처럼 String의 특정 문자를 찾을 때 사용할 수 있도록 해주는 식이며 아래처럼 + 또는 - 를 찾았을 경우 해당 값을 찾을 대체하여 문제를 해결하였습니다.

import Foundation

let input = readLine()!

let regexPattern = "[+-]"

let modifiedString = input.replacingOccurrences(of: regexPattern, with: " $0 ", options: .regularExpression)

var result = modifiedString.split(separator: " ").map { String($0) }

var minus = 0
var plus = 0
while !result.isEmpty {
    if result.first == "-" {
        while !result.isEmpty {
            if result.first != "+" && result.first != "-" {
                minus += Int(result.first!)!
            }
            result.removeFirst()
        }
    } else {
        if result.first != "+" {
            plus += Int(result.first!)!
        }
        result.removeFirst()

    }
}

print(plus-minus)

'Algorithm > Baekjoon' 카테고리의 다른 글

Swift - 백준 1927 최소 힙  (0) 2024.09.01
Swift - 백준 2606번  (0) 2024.08.30
Swift - 1463번 1로 만들기  (0) 2024.08.28
Swift - 백준 1764번 듣보잡  (0) 2024.08.28
Swift - 백준 1620번  (0) 2024.08.28
ytw_developer