Skip to content

Latest commit

ย 

History

History

P1786

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
ย 
ย 
ย 
ย 
ย 
ย 

[baekjoon-1786] ์ฐพ๊ธฐ

image image

KMP ๋ฌธ์ž์—ด ๊ฒ€์ƒ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜

KMP : ๋ฌธ์ž์—ด ๊ฒ€์ƒ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜

์œ„ ๋งํฌ์— ๋งค์šฐ ์ž˜ ์„ค๋ช…๋˜์–ด ์žˆ๋‹ค. ์Šค์Šค๋กœ ๋ช‡ ๋ฒˆ ๋” ๊ตฌํ˜„ํ•ด๋ณด๋ฉด์„œ ์—ฐ์Šตํ•ด์•ผ ํ•  ๊ฒƒ ๊ฐ™๋‹ค.

์‹œ๊ฐ„ ์ดˆ๊ณผ ์ด์Šˆ - makePk ํ•จ์ˆ˜

static int[] makePk(String P) {
    int[] Pk = new int[P.length()];
    for (int i = 1; i < P.length(); i++) {
        int k = (i+1) / 2;
        while (k > 0 && !P.substring(0, k).equals(P.substring(i+1 - k, i+1)))
            k--;
        Pk[i] = k;
    }
    return Pk;
}

์ฒ˜์Œ์—๋Š” ์ด๋ ‡๊ฒŒ ์งฐ์—ˆ๋‹ค. substring์„ ํ†ตํ•ด ์ผ์ผ์ด ๋น„๊ตํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ์งœ๋ฉด์„œ๋„ ์‹œ๊ฐ„ ๊ฑฑ์ •์„ ๋งŽ์ด ํ–ˆ์—ˆ๋Š”๋ฐ, ์—ญ์‹œ ์‹œ๊ฐ„ ์ดˆ๊ณผ ์ด์Šˆ๊ฐ€ ๋‚ฌ๋‹ค. ์œ„ ๋ธ”๋กœ๊ทธ๋ฅผ ์ฐธ๊ณ ํ•ด๋ณด๋‹ˆ ์ด ํ•จ์ˆ˜๋„ kmp ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์›๋ฆฌ๋ฅผ ์ด์šฉํ•ด์•ผ ํ•˜๋Š” ๊ฒƒ์ด์—ˆ๋‹ค. ๊ทธ๋žฌ์„ ๋•Œ O(P์˜ ๊ธธ์ด)๋กœ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค.

๋ฉ”๋ชจ๋ฆฌ์™€ ์‹œ๊ฐ„ ์ค„์ด๊ธฐ

image

์ฒ˜์Œ์—๋Š” ArrayList์— ๊ฒฐ๊ณผ๋ฅผ ์ €์žฅํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ•˜์˜€๋‹ค. ํ•˜์ง€๋งŒ ๊ทธ๋žฌ์„ ๋•Œ ์‹คํ–‰ ์‹œ๊ฐ„๊ณผ ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ๋„ˆ๋ฌด ๋งŽ์ด ํ•„์š”ํ•˜๋‹ค๋Š” ๊ฒƒ์„ ํ™•์ธํ•˜๊ณ  ๋‹ค๋ฅธ ์ฝ”๋“œ๋“ค์„ ์ฐธ๊ณ ํ•ด๋ณด์•˜๋‹ค. ArrayList ๋Œ€์‹ , StringBuilder์— ๊ฐ’์„ ์ €์žฅํ•˜์—ฌ ๊ทธ๋Œ€๋กœ ์ถœ๋ ฅํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ•˜๋‹ˆ ๋ฉ”๋ชจ๋ฆฌ์™€ ์‹œ๊ฐ„์„ ํฌ๊ฒŒ ์ค„์ผ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

ArrayList๋Š” ๋Œ€๋Ÿ‰์˜ ์ž๋ฃŒ๋ฅผ ์ถ”๊ฐ€ํ•  ์‹œ ๋ณต์‚ฌ๊ฐ€ ์ผ์–ด๋‚˜๊ฒŒ ๋˜์–ด ์„ฑ๋Šฅ ์ €ํ•˜๋ฅผ ์ผ์œผํ‚จ๋‹ค๊ณ  ํ•œ๋‹ค.

Java.util.ArrayList ์—์„œ add()๋‚˜ ensureCapicity() ๋ฅผ ํ˜ธ์ถœํ•˜์˜€์„ ๋•Œ
๋งŒ์•ฝ ์ง€๊ธˆ ํ• ๋‹น๋œ ์˜์—ญ์ด ์ž‘๋‹ค๋ฉด, (ํ˜„์žฌํฌ๊ธฐ*3/2+1)๋งŒํผ์œผ๋กœ ์ƒˆ๋กœ ์˜์—ญ์„ ํ• ๋‹นํ•˜๊ณ  ์ „์ฒด ๋ณต์‚ฌ๋ฅผ ํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.
Size๊ฐ€ ์ปค์ง€๋ฉด Arrays.copyOf() ๋‚ด๋ถ€์—์„œ ๋ณต์‚ฌํ•  ๋ถ€๋ถ„์ด ์ปค์ง‘๋‹ˆ๋‹ค.
๋‹ค๋ฅด๊ฒŒ ๋งํ•˜๋ฉด ํฌ๊ธฐ๊ฐ€ ์ปค์ง€๋ฉด ์‚ฌ์ด์ฆˆ ์ฆ๊ฐ€์— ๋ถ€๋‹ด์ด ๋œ๋‹ค๋Š” ๋ง์ด์ง€์š”.

์ถœ์ฒ˜ : Java ArrayList, Vector, LinkedList ์ž๋ฃŒํ˜• ๋น„๊ต (์‹œ๊ฐ„ ๋ณต์žก๋„ ์ค‘์‹ฌ์œผ๋กœ...) - ์‚ถ, ๊ธˆ์œต, IT, ์žก๋™์‚ฌ๋‹ˆ