๐ŸŒฟPython ๊ณตํ†ต๋œ ์‹œ์ž‘ ๋‹จ์–ด (prefix)

may_soouuยท2020๋…„ 9์›” 5์ผ
0

๋งค์ผ ์˜ค์ „ ์ง„ํ–‰ํ•˜๋Š” ์ฝ”๋“œ์นดํƒ€ ๋ฌธ์ œ ํ’€์ด๋ฅผ ํ•˜๋‹ค๊ฐ€, ํ’€๋ฆด ๋“ฏ ๋ง ๋“ฏ,, ํ•˜๋‹ค ๊ฒฐ๊ตญ ํ’€์ง€ ๋ชปํ–ˆ๋˜ ๋ฌธ์ œ ๐Ÿ˜‚

๐ŸŒ ๋ฌธ์ œ

strs์€ ๋‹จ์–ด๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.
๊ณตํ†ต๋œ ์‹œ์ž‘ ๋‹จ์–ด(prefix)๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ์„ธ์š”.
์˜ˆ๋ฅผ ๋“ค์–ด
strs = ['start', 'stair', 'step']
return์€ 'st'
strs = ['start', 'wework', 'today']
return์€ ''

1. ๋‚ด๊ฐ€ ์ƒ๊ฐํ–ˆ๋˜ ๋ฐฉ๋ฒ•

def get_prefix(strs):
      
    new_list = []
    other_list = []
    k = 0
    for i in range(len(strs)):
        new_list.append(strs[i][k]) 
        # ๊ฐ ๋ฆฌ์ŠคํŠธ์˜ ์ฒซ๋ฒˆ์งธ ๊ธ€์ž๋ฅผ ์ƒˆ๋กœ์šด ๋ฆฌ์ŠคํŠธ์— ๋‹ด๊ธฐ
	if new_list.count(new_list[0]) == len(new_list):
    	# ์ฒซ ๋ฒˆ์งธ ๊ธ€์ž๋ฅผ ์นด์šดํŠธ ํ•œ ์ˆซ์ž์™€ ๋ฆฌ์ŠคํŠธ์˜ ๊ธธ์ด๊ฐ€ ๊ฐ™์œผ๋ฉด
        # (์ฆ‰, ๋ฆฌ์ŠคํŠธ ์•ˆ ๊ธ€์ž๊ฐ€ ๋ชจ๋‘ ๊ฐ™์€ ๊ธ€์ž์ผ ๋•Œ)
            # ์ƒˆ๋กœ์šด ๋ฆฌ์ŠคํŠธ์— ์ฒซ๋ฒˆ์งธ ๊ธ€์ž๋ฅผ ๋„ฃ๊ณ 
            other_list.append(new_list[0])
            # ๊ธฐ์กด ๋ฆฌ์ŠคํŠธ๋Š” clear
            new_list.clear()
            k += 1
       # ๋งŒ์•ฝ, ๊ธ€์ž ์นด์šดํŠธ ํ•œ ์ˆซ์ž์™€ ๊ธธ์ด๊ฐ€ ๋‹ค๋ฅด๋ฉด 
    	elif new_list.count(new_list[0]) != len(new_list):
           #๋ฆฌ์ŠคํŠธ๋งŒ ํด๋ฆฌ์–ด
            new_list.clear()
            break

์ด๋ ‡๊ฒŒ ํ’€๋ฉด์„œ ๊ฐ™์œผ๋ฉด ๊ทธ ๋ฌธ์ž๋ฅผ ์ƒˆ๋กœ์šด ๋ฆฌ์ŠคํŠธ์— ์ฐจ๊ณก์ฐจ๊ณก append ํ•ด์„œ ๊ธธ์ด๋ฅผ ๊ตฌํ•˜๋ ค๊ณ  ํ–ˆ๋‹ค!! ๊ทผ๋ฐ ์ƒ๊ฐ๋ณด๋‹ค ์ž๊พธ index ์˜ค๋ฅ˜์™€ elif์˜ ๊ฒฝ์šฐ์ธ๋ฐ๋„ ๋ฆฌ์ŠคํŠธ์— append๋ผ์„œ ๊ฒฐ๊ตญ ๊ตฌ๊ธ€๋ง ใ… ใ… 

2. ํ•ด๊ฒฐ๋ฐฉ๋ฒ•

def get_prefix(strs):
 if len(strs) == 0:
   return ''
 
 res = ''
 strs = sorted(strs)

   for i in strs[0]:
       if strs[-1].startswith(res+i):
           res += i
       else:
           break
   return res
  • sort()
    ์ •๋ ฌํ•˜๋Š” ํ•จ์ˆ˜๋‹ค. sort ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด ์•ŒํŒŒ๋ฒณ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌํ•œ๋‹ค.
    ex. string, start, stick > start stick string ์ด๋ ‡๊ฒŒ !

  • startswith
    ๊ด„ํ˜ธ ์•ˆ์— ์žˆ๋Š” ๋‹จ์–ด๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋งค์น˜์‹œ์ผœ์ฃผ๋Š” ํ•จ์ˆ˜
profile
back-end ๊ฐœ๋ฐœ์ž

0๊ฐœ์˜ ๋Œ“๊ธ€