๋งค์ผ ์ค์ ์งํํ๋ ์ฝ๋์นดํ ๋ฌธ์ ํ์ด๋ฅผ ํ๋ค๊ฐ, ํ๋ฆด ๋ฏ ๋ง ๋ฏ,, ํ๋ค ๊ฒฐ๊ตญ ํ์ง ๋ชปํ๋ ๋ฌธ์ ๐
strs์ ๋จ์ด๊ฐ ๋ด๊ธด ๋ฐฐ์ด์ ๋๋ค.
๊ณตํต๋ ์์ ๋จ์ด(prefix)๋ฅผ ๋ฐํํด์ฃผ์ธ์.
์๋ฅผ ๋ค์ด
strs = ['start', 'stair', 'step']
return์ 'st'
strs = ['start', 'wework', 'today']
return์ ''
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๋ผ์ ๊ฒฐ๊ตญ ๊ตฌ๊ธ๋ง ใ ใ
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