ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๊ฐ€์žฅ ๊ธด ํŒฐ๋ฆฐ๋“œ๋กฌ

์•ž๋’ค๋ฅผ ๋’ค์ง‘์–ด๋„ ๋˜‘๊ฐ™์€ ๋ฌธ์ž์—ด์„ ํŒฐ๋ฆฐ๋“œ๋กฌ(palindrome)์ด๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๋ฌธ์ž์—ด s๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ, s์˜ ๋ถ€๋ถ„๋ฌธ์ž์—ด(Substring)์ค‘ ๊ฐ€์žฅ ๊ธด ํŒฐ๋ฆฐ๋“œ๋กฌ์˜ ๊ธธ์ด๋ฅผ return ํ•˜๋Š” solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด ์ฃผ์„ธ์š”. ์˜ˆ๋ฅผ๋“ค

programmers.co.kr

 

๋ฌธ์ œ ํ’€์ด

๋ฌธ์ž์—ด์ด ์ฃผ์–ด์งˆ ๋•Œ, ๋ฌธ์ž์—ด์˜ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด ์ค‘ ๊ฐ€์žฅ ๊ธด ํŒฐ๋ฆฐ๋“œ๋กฌ์„ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค. ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์œ„ํ•ด์„œ๋Š” `2์ค‘ ๋ฐ˜๋ณต๋ฌธ`์„ ํ†ตํ•ด ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์˜ ์‹œ์ž‘ ์œ„์น˜์™€ ๋ ์œ„์น˜๋ฅผ ์„ค์ • ํ›„ ํŒฐ๋ฆฐ๋“œ๋กฌ์ธ์ง€ ํ™•์ธํ•˜๋ฉด ๋œ๋‹ค.

 

์ฝ”๋“œ

def solution(s):
    answer = -1
    for i in range(len(s)):
        for j in range(i + 1, len(s) + 1):
            cur_string = s[i:j]
            # ๊ธฐ์กด์— ์ฐพ์€ ๊ธธ์ด๋ณด๋‹ค ์ž‘๋‹ค๋ฉด, ์Šคํ‚ต.
            if len(cur_string) <= answer:
                continue
            # ํŽ ๋ฆฐ๋“œ๋กฌ์ด๋ผ๋ฉด, ์ตœ๋Œ€๊ธธ์ด์™€ ๋น„๊ต.    
            if cur_string == cur_string[::-1]:
                if answer < len(cur_string):
                    answer = len(cur_string)
    return answer

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€