# ํŠธ๋ผ์ด(Trie)



๋ฌธ์ž์—ด์—์„œ ๊ฒ€์ƒ‰์„ ๋น ๋ฅด๊ฒŒ ๋„์™€์ฃผ๋Š” ์ž๋ฃŒ๊ตฌ์กฐ

์ •์ˆ˜ํ˜•์—์„œ ์ด์ง„ํƒ์ƒ‰ํŠธ๋ฆฌ๋ฅผ ์ด์šฉํ•˜๋ฉด ์‹œ๊ฐ„๋ณต์žก๋„ O(logN)
ํ•˜์ง€๋งŒ ๋ฌธ์ž์—ด์—์„œ ์ ์šฉํ–ˆ์„ ๋•Œ, ๋ฌธ์ž์—ด ์ตœ๋Œ€ ๊ธธ์ด๊ฐ€ M์ด๋ฉด O(M*logN)์ด ๋œ๋‹ค.

ํŠธ๋ผ์ด๋ฅผ ํ™œ์šฉํ•˜๋ฉด? โ†’ O(M)์œผ๋กœ ๋ฌธ์ž์—ด ๊ฒ€์ƒ‰์ด ๊ฐ€๋Šฅํ•จ!

์˜ˆ์‹œ ๊ทธ๋ฆผ์—์„œ ์ฃผ์–ด์ง€๋Š” ๋ฐฐ์—ด์˜ ์ด ๋ฌธ์ž์—ด ๊ฐœ์ˆ˜๋Š” 8๊ฐœ์ธ๋ฐ, ํŠธ๋ผ์ด๋ฅผ ํ™œ์šฉํ•œ ํŠธ๋ฆฌ์—์„œ๋„ ๋งˆ์ง€๋ง‰ ๋๋‚˜๋Š” ๋…ธ๋“œ๋งˆ๋‹ค '๋„ค๋ชจ' ๋ชจ์–‘์œผ๋กœ ๊ตฌ์„ฑ๋œ ๊ฒƒ์„ ํ™•์ธํ•˜๋ฉด ์ด 8๊ฐœ๋‹ค.


ํ•ด๋‹น ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ํ’€์–ด๋ณด๊ธฐ ์œ„ํ•ด ์ข‹์€ ๋ฌธ์ œ : ๋ฐฑ์ค€ 5052(์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก) (opens new window)

# ๋ฌธ์ œ์—์„œ Trie๋ฅผ java๋กœ ๊ตฌํ˜„ํ•œ ์ฝ”๋“œ

static class Trie {
    boolean end;
    boolean pass;
    Trie[] child;

    Trie() {
        end = false;
        pass = false;
        child = new Trie[10];
    }

    public boolean insert(String str, int idx) {

        //๋๋‚˜๋Š” ๋‹จ์–ด ์žˆ์œผ๋ฉด false ์ข…๋ฃŒ
        if(end) return false;

        //idx๊ฐ€ str๋งŒํผ ์™”์„๋•Œ
        if(idx == str.length()) {
            end = true;
            if(pass) return false; // ๋” ์ง€๋‚˜๊ฐ€๋Š” ๋‹จ์–ด ์žˆ์œผ๋ฉด false ์ข…๋ฃŒ
            else return true;
        }
        //์•„์ง ์•ˆ์™”์„ ๋•Œ
        else {
            int next = str.charAt(idx) - '0';
            if(child[next] == null) {
                child[next] = new Trie();
                pass = true;
            }
            return child[next].insert(str, idx+1);
        }

    }
}
์ตœ์ข… ์ˆ˜์ • : 12/17/2022, 7:23:59 AM