๋ฐฑ์ค€ - ์ปตํ™€๋”(Swift)

2022. 11. 4. 15:09ใ†Algorithm

๋ฐฑ์ค€ - ์ปตํ™€๋”(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

https://www.acmicpc.net/problem/2810

 

2810๋ฒˆ: ์ปตํ™€๋”

์ฒซ์งธ ์ค„์— ์ขŒ์„์˜ ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ N ≤ 50) ๋‘˜์งธ ์ค„์—๋Š” ์ขŒ์„์˜ ์ •๋ณด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.

www.acmicpc.net

 

 ๋‚˜์˜ ํ’€์ด

 

์ž…๋ ฅ์กฐ๊ฑด์ด ์ž‘์•„์„œ *์„ ๊ทœ์น™์— ๋งž๊ฒŒ ์‚ฝ์ž…ํ•œ ๋’ค ์Šคํƒ์„ ์ด์šฉํ•ด์„œ ์—†์•ด๋‹ค.

 

import Foundation

let n = Int(readLine()!)!
var stack = [Character]()
var str = String(readLine()!)
str = str.replacingOccurrences(of: "S", with: "*S*")
str = str.replacingOccurrences(of: "LL", with: "*LL*")
str = str.replacingOccurrences(of: "**", with: "*")
var arr = str.map{$0}
var cnt = 0

for x in arr {
    if x == "*" { //์ปตํ™€๋”์ผ ๋•Œ
        if !stack.isEmpty {
            stack.removeLast()
        } else {
            cnt += 1
        }
    } else { // ์‚ฌ๋žŒ์ด ๋“ค์–ด์˜ฌ ๋•Œ
        if cnt > 0 {
            cnt -= 1
        } else {
            stack.append(x)
        }
    }
}
print(n - stack.count)

 

๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด๋ฅผ ๋ณด๋‹ˆ ์ปตํ™€๋”์˜ ์ˆ˜๊ฐ€ ์‚ฌ๋žŒ์˜ ์ˆ˜๋ณด๋‹ค ์ž‘์„๋•Œ๋Š” ์ปตํ™€๋”์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋‹ต์ธ ๊ฒƒ์„ ์•Œ์•˜๋‹ค. 

์ฆ‰ ์ปตํ™€๋”๋Š” ์–ด๋Š๊ณณ์— ์œ„์น˜ํ•˜๋“  ์ „๋ถ€ ๋‹ค ์‚ฌ์šฉ์ด ๋œ๋‹ค๋Š” ๋œป์ด๋‹ค. 

ํ•˜์ง€๋งŒ SSS์ฒ˜๋Ÿผ ์ปตํ™€๋”๊ฐ€ ์‚ฌ๋žŒ์ˆ˜๋ณด๋‹ค ๋งŽ์€ ๊ฒฝ์šฐ๋Š” ์‚ฌ๋žŒ์˜ ์ˆ˜๊ฐ€ ์ปตํ™€๋”๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ˆ˜๊ฐ€ ๋œ๋‹ค.

 

import Foundation

let n = Int(readLine()!)!
var stack = [Character]()
var str = String(readLine()!)
str = str.replacingOccurrences(of: "S", with: "*S*")
str = str.replacingOccurrences(of: "LL", with: "*LL*")
str = str.replacingOccurrences(of: "**", with: "*")
var arr = str.map{$0}
var cnt = 0

let cupCount = Array(str).filter{$0 == "*"}.count
if cupCount < n {
    print(cupCount)
} else {
    print(n)
}