๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Programming/Coding Test

[Level 2] ์กฐ์ด์Šคํ‹ฑ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์กฐ์ด์Šคํ‹ฑ

์กฐ์ด์Šคํ‹ฑ์œผ๋กœ ์•ŒํŒŒ๋ฒณ ์ด๋ฆ„์„ ์™„์„ฑํ•˜์„ธ์š”. ๋งจ ์ฒ˜์Œ์—” A๋กœ๋งŒ ์ด๋ฃจ์–ด์ ธ ์žˆ์Šต๋‹ˆ๋‹ค. ex) ์™„์„ฑํ•ด์•ผ ํ•˜๋Š” ์ด๋ฆ„์ด ์„ธ ๊ธ€์ž๋ฉด AAA, ๋„ค ๊ธ€์ž๋ฉด AAAA ์กฐ์ด์Šคํ‹ฑ์„ ๊ฐ ๋ฐฉํ–ฅ์œผ๋กœ ์›€์ง์ด๋ฉด ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค. โ–ฒ - ๋‹ค

programmers.co.kr

 

def cnt_up_down(chr):
    cnt_from_a = abs(ord('A')-ord(chr))
    cnt_from_z = abs(ord('Z')-ord(chr)+1)
    
    return(min(cnt_from_a, cnt_from_z))

def solution(name):
    cnt = 0

    for i in name:
        cnt += cnt_up_down(i)

    lst_name = list(name)
    len_name = len(lst_name)
    
    
    if lst_name.count('A') == len_name:
        return 0

    cur = 0
    lst_name[cur] = 'A'
    

    while lst_name.count('A') != len_name:
        cnt_left = 0
        cnt_right = 0
    
        pos_right, pos_left = cur, cur

        for i in range(1, len_name):
            cnt_right += 1
            pos_right += 1
        
            if pos_right > len_name-1:
                pos_right -= len_name
            
            if lst_name[pos_right] != 'A':
                break
            
        for j in range(1, len_name):
            cnt_left += 1
            pos_left -= 1
        
            if pos_left < 0:
                pos_left += len_name
            
            if lst_name[pos_left] != 'A':
                break
            
        if cnt_right <= cnt_left:
            lst_name[pos_right] = 'A'
            cnt += cnt_right
            cur = pos_right
        else:
            lst_name[pos_left] = 'A'
            cnt += cnt_left
            cur = pos_left

    return cnt

 

โ–ท ์ด ๋ฌธ์ œ๋Š” ํฌ๊ฒŒ ์กฐ์ด์Šคํ‹ฑ์„ ์œ„/์•„๋ž˜๋กœ ์›€์ง์ด๋Š” ๊ฒฝ์šฐ์™€ ์ขŒ/์šฐ๋กœ ์›€์ง์ด๋Š” ๊ฒฝ์šฐ๋กœ ๋‚˜๋ˆ„์–ด ํ’€์–ด์•ผ ํ•œ๋‹ค. ์œ„/์•„๋ž˜๋กœ ์›€์ง์ด๋Š” ํšŸ์ˆ˜๋Š” ์–ด๋– ํ•œ ๊ฒฝ์šฐ์—๋„ ๊ฐ™๋‹ค. ๋”ฐ๋ผ์„œ ์ขŒ/์šฐ์˜ ์ด๋™์„ ์ค„์—ฌ์„œ ์ตœ์†Œ์˜ ์ด๋™ํšŸ์ˆ˜๋กœ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด ํ•ต์‹ฌ์ด๋‹ค.

 

โ–ท cnt_up_down ํ•จ์ˆ˜๋Š” ๋ฌธ์ž์— ๋Œ€ํ•œ ์œ„/์•„๋ž˜๋กœ ์›€์ง์—ฌ์•ผ ํ•˜๋Š” ํšŸ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜์ด๋‹ค.

 

โ–ท ์œ„ ์ฝ”๋“œ์˜ ๋…ผ๋ฆฌ๋ฅผ ์š”์•ฝํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

 

1. cnt_up_down ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ ์œ„/์•„๋ž˜๋กœ ์›€์ง์ด๋Š” ํšŸ์ˆ˜๋ฅผ ๊ตฌํ•œ๋‹ค.

2. ์ฒซ ๋ฒˆ์งธ ์œ„์น˜์˜ ๋ฌธ์ž๋ฅผ A๋กœ ๋ณ€๊ฒฝํ•œ๋‹ค.

3. ์ฒซ ๋ฒˆ์งธ ์œ„์น˜๋ฅผ ํ˜„์žฌ ์œ„์น˜๋กœ ์ •ํ•œ ๋’ค, ์™ผ์ชฝ์œผ๋กœ ์ด๋™ํ•˜๋Š” ๊ฒฝ์šฐ์™€ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ด๋™ํ•˜๋Š” ๊ฒฝ์šฐ์˜ ์ด๋™ํšŸ์ˆ˜๋ฅผ ๋น„๊ตํ•œ๋‹ค. ์ด๋•Œ ๋‘˜ ์ค‘ ์ž‘์€ ์ด๋™ํšŸ์ˆ˜๋ฅผ ์ „์ฒด ์ด๋™ํšŸ์ˆ˜์— ์ถ”๊ฐ€ํ•˜๊ณ , ํ˜„์žฌ ์œ„์น˜๋ฅผ ํ•ด๋‹น ์ด๋™์„ ๋ฐ˜์˜ํ•˜์—ฌ ๋ณ€๊ฒฝํ•œ๋‹ค. ์ด๋•Œ ๋ณ€๊ฒฝ๋œ ํ˜„์žฌ์œ„์น˜์˜ ๋ฌธ์ž๋ฅผ A๋กœ ๋ณ€๊ฒฝํ•œ๋‹ค.

4. name ๋ณ€์ˆ˜์˜ ๋ชจ๋“  ๋ฌธ์ž๊ฐ€ A๊ฐ€ ๋  ๋•Œ๊นŒ์ง€ 3๋ฒˆ ์ž‘์—…์„ ๋ฐ˜๋ณตํ•œ๋‹ค.