๋ฐฑ์ค - ์ปตํ๋(Swift)
2022. 11. 4. 15:09ใAlgorithm
๋ฐฑ์ค - ์ปตํ๋(Swift)
๋ฌธ์ ์ค๋ช
https://www.acmicpc.net/problem/2810
๋์ ํ์ด
์ ๋ ฅ์กฐ๊ฑด์ด ์์์ *์ ๊ท์น์ ๋ง๊ฒ ์ฝ์ ํ ๋ค ์คํ์ ์ด์ฉํด์ ์์ด๋ค.
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)
}
'Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค - UCPC๋ ๋ฌด์์ด ์ฝ์์ผ๊น?(Swift) (0) | 2022.11.06 |
---|---|
๋ฐฑ์ค - A์ B(Swift) (0) | 2022.11.06 |
๋ฐฑ์ค - ์ผ์(Swift) (0) | 2022.11.04 |
๋ฐฑ์ค - ๊ณตํญ(Swift) (0) | 2022.11.03 |
๋ฐฑ์ค - ํฌ๊ฒ ๋ง๋ค๊ธฐ(Swift) (0) | 2022.11.03 |