TIL 003 LCP/LCS

์กฐ์„ฑํ˜„ยท2020๋…„ 12์›” 27์ผ
0

์ •๊ธ€

๋ชฉ๋ก ๋ณด๊ธฐ
4/21

๐Ÿ“• LCP (Longest common prefix)

๐Ÿ‘‰ ์‚ฌ์šฉ๋ชฉ์ 
์ •๋ ฌ๋œ ์ ‘๋ฏธ์‚ฌ(SA)์—์„œ ์ธ์ ‘ํ•œ ์ ‘๋ฏธ์‚ฌ๋“ค๋ผ๋ฆฌ(๋ฐ”๋กœ ๋’ค), ๋ช‡ ์นธ๊นŒ์ง€ ๊ฒน์น˜๋ฅผ ๋‹ด์€ ๋ฐฐ์—ด. ๋ฐ˜๋ณต๋œ ๊ฐ€์žฅ ๊ธด ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์„ ๋น ๋ฅด๊ฒŒ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.
SA์˜ ์‘์šฉ ๋ฐฐ์—ด๋กœ O(N)์œผ๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

ex) banana

๐Ÿ‘‰ ๊ตฌํ˜„๋ฐฉ๋ฒ•
LCP ๋ฐฐ์—ด์˜ ํŠน์ง•์€ ์–ด๋–ค ๋‘ ์ธ์ ‘ํ•œ ์ ‘๋ฏธ์‚ฌ X, Y๊ฐ€ ์žˆ๊ณ  ๊ทธ๋“ค์˜ LCP ๊ฐ’์ด z(>0)๋ฉด, X, Y์—์„œ ์•ž์˜ ํ•œ ๊ธ€์ž์”ฉ์„ ๋บ€ ๊ฒƒ ์—ญ์‹œ ์ ‘๋ฏธ์‚ฌ์ด๋ฉฐ, ์ด๋“ค์˜ LCP ๊ฐ’์€ ์ตœ์†Œ z-1์ด๋‹ค.

์ด๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์•ž์—์„œ๋ถ€ํ„ฐ ํ•œ๊ธ€์ž์”ฉ ๋บ€ ์ ‘๋ฏธ์‚ฌ์˜ LCP ๊ฐ’์„ ๊ตฌํ•œ๋‹ค

ex) banana
banana -> na -> LCP = 0
anana -> banana -> LCP = 0
nana -> x -> LCP = x
ana -> anana -> LCP = 3(z)
na -> nana -> LCP = 2(z-1)
a -> ana -> LCP = 1(z-1)

๐Ÿ‘‰ ๋งํฌ
์•„๋ž˜๋งํฌ์— ์ž์„ธํžˆ ์„ค๋ช…๋˜์–ด์žˆ๋‹ค.

์ ‘๋ฏธ์‚ฌ๋ฐฐ์—ด
https://blog.naver.com/kks227/221028710658

๐Ÿ“• LCS (Longest common subsequence)

๐Ÿ‘‰ ์‚ฌ์šฉ๋ชฉ์ 
์ตœ์žฅ ๊ณตํ†ต ๋ถ€๋ถ„ ๋ฌธ์ž์—ด.
๋‘ ๋‹จ์–ด ์ค‘์— ๊ฒน์น˜๋Š” ๋ฌธ์ž์—ด ์ค‘ ๊ฐ€์žฅ ๊ธด ๋ฌธ์ž์—ด

๐Ÿ‘‰ ๊ตฌํ˜„๋ฐฉ๋ฒ•
๋‘ ๋‹จ์–ด๋ฅผ ๋ถ™์—ฌ์„œ LCP๋ฅผ ๊ตฌํ•œ๋‹ค.
์ด ๋•Œ ๋‘ ๋‹จ์–ด ์‚ฌ์ด์— '#','$'๋“ฑ์˜ ๊ธฐํ˜ธ๋ฅผ ์„ž์–ด ๊ตฌ๋ถ„ ์‹œ์ผœ ์ค€๋‹ค.
LCS๋Š” LCP์ค‘ ์ตœ๋Œ€๊ฐ’์ด ์•„๋‹Œ, ๋ฐ˜๋Œ€์ชฝ์˜ ๊ธ€์ž๊ฐ€ ํ•œ ๊ธ€์ž๋ผ๋„ ๋“ค์–ด ์žˆ๋Š” ๋‹จ์–ด์˜ LCP ์ค‘ ์ตœ๋Œ€๊ฐ’์ด๋‹ค.
์ฆ‰, SA์—์„œ ์ธ์ ‘ํ•œ ๋ฌธ์ž์—ด์ด ๋ฐ˜๋Œ€์ชฝ์— ์žˆ๋Š” ์ง€ ํ™•์ธ์„ ํ•ด์•ผํ•œ๋‹ค.

ex)
1. abcdabcdabcd
2. abcds
-> abcdabcdabcd#abcds
LCS = 4 ('abcd')

๐Ÿ‘‰ ๋งํฌ
์•„๋ž˜๋งํฌ์— ์ž์„ธํžˆ ์„ค๋ช…๋˜์–ด์žˆ๋‹ค.

์ ‘๋ฏธ์‚ฌ๋ฐฐ์—ด
https://blog.naver.com/kks227/221028710658

profile
Jazzing๐Ÿ‘จโ€๐Ÿ’ป

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