2941을 풀 때 크로아티아어 알파벳을 제거하는 알고리즘으로 구현했습니다.
나머지 알파벳은 크로아티아어 알파벳으로 병합되었습니다 …
그래서 빈 문자열로 바꾸도록 변경했습니다.
import Foundation
var str = readLine()!
var count = 0
while true {
if str.contains("c=") {
count += 1
str.replaceSubrange(str.range(of: "c=")!, with: " ")
} else if str.contains("c-") {
count += 1
str.replaceSubrange(str.range(of: "c-")!, with: " ")
} else if str.contains("d-") {
count += 1
str.replaceSubrange(str.range(of: "d-")!, with: " ")
} else if str.contains("lj") {
count += 1
str.replaceSubrange(str.range(of: "lj")!, with: " ")
} else if str.contains("nj") {
count += 1
str.replaceSubrange(str.range(of: "nj")!, with: " ")
} else if str.contains("s=") {
count += 1
str.replaceSubrange(str.range(of: "s=")!, with: " ")
} else if str.contains("dz=") {
count += 1
str.replaceSubrange(str.range(of: "dz=")!, with: " ")
} else if str.contains("z=") {
count += 1
str.replaceSubrange(str.range(of: "z=")!, with: " ")
} else {
break
}
}
for i in str {
if i != " " {
count += 1
}
}
print(count)
내용과 동시에 확인하고 싶었지만 방법이 없을 것 같아서 하나씩 적어보았습니다.
dz=는 z= 앞에 와야 합니다. z=가 먼저 오면 크로아티아어 dz=가 d와 z=로 분리되기 때문입니다.
제출 후 여러 블로그를 탐색하고 코드가 얼마나 짧은지 놀랐습니다.
그래서 다시 수정을 시도했습니다.
import Foundation
var str = readLine()!
let croatiaAlpha = ("c=", "c-", "d-", "lj", "nj", "s=", "dz=", "z=")
for index in 0...croatiaAlpha.count - 1 {
str = str.replacingOccurrences(of: croatiaAlpha(index), with: " ")
}
print(str.count)
replaceOccurrences()라는 메소드를 사용하기 때문에 한번에 해결 가능..!
그건 소용 없어!