๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“– Problem Solution

[Swift] Baekjoon ํŒฐ๋ฆฐ๋“œ๋กฌ ๋งŒ๋“ค๊ธฐ 1254๋ฒˆ

by Fomagran ๐Ÿ’ป 2022. 1. 6.
728x90
๋ฐ˜์‘ํ˜•

Problem

 

 

1254๋ฒˆ: ํŒฐ๋ฆฐ๋“œ๋กฌ ๋งŒ๋“ค๊ธฐ

๋™ํ˜ธ์™€ ๊ทœ์™„์ด๋Š” 212ํ˜ธ์—์„œ ๋ฌธ์ž์—ด์— ๋Œ€ํ•ด ๊ณต๋ถ€ํ•˜๊ณ  ์žˆ๋‹ค. ๊ทœ์™„์ด๋Š” ํŒฐ๋ฆฐ๋“œ๋กฌ์„ ์—„์ฒญ๋‚˜๊ฒŒ ์ข‹์•„ํ•œ๋‹ค. ํŒฐ๋ฆฐ๋“œ๋กฌ์ด๋ž€ ์•ž์—์„œ๋ถ€ํ„ฐ ์ฝ์œผ๋‚˜ ๋’ค์—์„œ๋ถ€ํ„ฐ ์ฝ์œผ๋‚˜ ๊ฐ™๊ฒŒ ์ฝํžˆ๋Š” ๋ฌธ์ž์—ด์„ ๋งํ•œ๋‹ค. ๋™ํ˜ธ๋Š”

www.acmicpc.net


Solution

 

1. ์ฃผ์–ด์ง„ ๋ฌธ์ž๋ฅผ ๋’ค์ง‘์–ด์„œ ๋’ค์— ๋ถ™์ธ๋‹ค.

 

var str = readLine()!
var newStr = (str + str.reversed()).map{String($0)}

 

2. ๋’ค์— ๋ถ™์ธ ๊ณณ์„ ์‹œ์ž‘์ ์œผ๋กœ ์ฃผ์–ด์ง„ ๋ฌธ์ž๊ฐ€ ๋  ๋•Œ๊นŒ์ง€ ์‚ญ์ œํ•œ๋‹ค.

 

while newStr.count >= str.count {
    if isPalindrome(newStr) {
        min = newStr.count
    }
    if newStr.count == str.count {
        break
    }
    newStr.remove(at: start)
}

 

3. ํŒฐ๋ฆฐ๋“œ๋กฌ์„ ํ™•์ธํ•˜๊ณ  ์ตœ์†Œ ๊ธธ์ด๋ฅผ ๊ฐฑ์‹ ํ•œ๋‹ค.

 

func isPalindrome(_ str:[String]) -> Bool {
    let middle = str.count%2 == 0 ? str.count/2-1 : str.count/2
    let head = str[0...middle].joined()
    let tail = str[str.count/2..<str.count].reversed().joined()
    return head == tail
}

Source Code

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€