๋ฌธ์ ํด๊ฒฐ ๊ณผ์
์ฒ์์๋ ์๋ ์์์ฒ๋ผ quack / quack์ด๋ผ ๋๋ง๋ฆฌ์ธ์ค ์์๋๋ฐ ์๊ณ ๋ณด๋ ์ฐ์๋ quack์ ํ๋ง๋ฆฌ์๋๊ฑฐ์!!
๊ทธ๋ฆฌ๊ณ ์ธ์์๋ฆฌ๋ฅผ ์ ๋ถ ์ฌ์ฉํด์ผ ํ๋ค๋ ๋ถ๋ถ์ด ์ข ํท๊ฐ๋ ธ๋ค.
๊ทธ๋์ ์ ์์ ์ธ ์ธ์์๋ฆฌ๊ฐ ์๋ ๊ฒฝ์ฐ
- q๋ก ์์ํ์ง ์๊ฑฐ๋
- k๋ก ๋๋์ง ์๊ฑฐ๋
- ์ธ์์๋ฆฌ ์ ์ฒด๊ฐ 5๋ก ๋๋์ด๋จ์ด์ง์ง ์์ผ๋ฉด -1์ ์ถ๋ ฅํด์ฃผ์๋ค.
duckSound[0] != "q" || duckSound[soundCnt-1] != "k" || soundCnt % 5 != 0
๋ํ ์ธ์ ์๋ฆฌ์ ์๋ ๋ง์ง๋ง ์ ์์์ฒ๋ผ ์ด์ํ ์ธ์์๋ฆฌ๋ฅผ ๊ฑฐ๋ฅด๊ธฐ ์ํด ์๋์ ๊ฐ์ ์กฐ๊ฑด ์ถ๊ฐํ๋ค.
if duckSound[i] == "q" && visited[i] == 0 {
getDuckCnt(i)
}
getDuckCnt
func getDuckCnt(_ start: Int) {
var idx = 0 //quack์ฉ index
var isNewDuck = true //์๋ก์ด ์ค๋ฆฌ์ธ์ง ์๋์ง
for i in start..<soundCnt {
if duckSound[i] == quack[idx] && visited[i] == 0 {
idx += 1
visited[i] = 1
if duckSound[i] == "k" {
idx = 0
if isNewDuck {
duckCnt += 1
isNewDuck = false
}
}
}
}
}
์ฌ๊ธฐ์๋ quack ๋ฐฐ์ด์ ๋ง๋ค๊ณ , quack ์ ์ฉ idx๋ฅผ ๋ง๋ค์ด์ ์ธ์์๋ฆฌ์ quack์ ํ๋์ฉ ๋น๊ตํ๊ณ ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ
์๋ก์ด ์ค๋ฆฌ์ธ์ง ์๋์ง ํ์ธํด์ฃผ๋ ๋ณ์๋ฅผ ์ถ๊ฐ
๋ง์ฝ์ ์๋ก์ด ์ค๋ฆฌ๋ผ๋ฉด duckCnt += 1ํด์ฃผ๊ณ
isNewDuck = false ๋ฐ๊ฟ์ฃผ๋ฉด์
k ๋ค์ q๊ฐ ์ค๋ ํ๋ง๋ฆฌ์ ์ค๋ฆฌ๊ฐ ์ฐ๋ ์ํฉ์ ๋๋น
if duckCnt == 0 || visited.contains(0) {
print(-1)
} else {
print(duckCnt)
}
์ค๋ฆฌ์ ์๊ฐ 0์ด๊ฑฐ๋ ๋ฐฉ๋ฌธํ์ง ์์ ์ธ์์๋ฆฌ๊ฐ ์๋ค๋ฉด
์ด ๋ํ ์ ์์ ์ธ ์ธ์์๋ฆฌ๊ฐ ์๋๊ธฐ ๋๋ฌธ์ -1
๋์ ํ์ด
func getDuckCnt(_ start: Int) {
var idx = 0 //quack์ฉ index
var isNewDuck = true //์๋ก์ด ์ค๋ฆฌ์ธ์ง ์๋์ง
for i in start..<soundCnt {
if duckSound[i] == quack[idx] && visited[i] == 0 {
idx += 1
visited[i] = 1
if duckSound[i] == "k" {
idx = 0
if isNewDuck {
duckCnt += 1
isNewDuck = false
}
}
}
}
}
let duckSound = readLine()!.map { String($0) }
let soundCnt = duckSound.count
var visited = Array(repeating: 0, count: soundCnt)
let quack = ["q", "u", "a", "c", "k"]
var duckCnt = 0 // ์ถ๋ ฅํด์ผ ํ ์ค๋ฆฌ ์
if duckSound[0] != "q" || duckSound[soundCnt-1] != "k" || soundCnt % 5 != 0 {
print(-1)
} else {
for i in 0..<soundCnt {
if duckSound[i] == "q" && visited[i] == 0 {
getDuckCnt(i)
}
}
if duckCnt == 0 || visited.contains(0) {
print(-1)
} else {
print(duckCnt)
}
}
'Algorithm > Swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] ๊ตฌ๋ฆ - 1์ฐจ์ ๋ฟ์๋ฟ์ (0) | 2024.07.03 |
---|---|
[Swift] ํ๋ก๊ทธ๋๋จธ์ค - ํน์ ๋ฌธ์์ด๋ก ๋๋๋ ๊ฐ์ฅ ๊ธด ๋ถ๋ถ ๋ฌธ์์ด ์ฐพ๊ธฐ (0) | 2024.06.19 |