LV.2 ์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก

 

1. ๋ฌธ์ œ : Link

์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก์—์„œ ํ•œ ์ „ํ™”๋ฒˆํ˜ธ๊ฐ€ ๋‹ค๋ฅธ ์ „ํ™”๋ฒˆํ˜ธ์˜ ์ ‘๋‘์–ด๊ฐ€ ๋˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ์œผ๋ฉด False return

 

2. ํ’€์ด

๋ฐฐ์—ด์„ ์ˆœํšŒํ•˜๋ฉด์„œ ๋ฌธ์ž์—ด์„ ํ•˜๋‚˜์”ฉ ๋น„๊ต

-> ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋Š” ๋ชจ๋‘ ํ†ต๊ณผํ–ˆ์ง€๋งŒ ํšจ์œจ์„ฑ์—์„œ runtime error

 

3. ์ฝ”๋“œ

def solution(phone_book):
    answer = True

    if len(phone_book) == 1:
        return answer
    
    phone_book.sort(key = len)

    cnt = 0
    for i in range(len(phone_book)-1):
        for k in range(i+1, len(phone_book)):
            for j in range(len(phone_book[i])):
                if phone_book[i][j] != phone_book[k][j]:
                    break
                else:

์ˆ˜์ •)

def solution(phone_book):
    answer = True
    dic = {}

    for p in phone_book:
        dic[p] = 1

    for p in phone_book:
        tmp = ""
        for num in p:
            tmp += num
            if tmp in dic and tmp!=p:
                answer = False

    return answer

dic ์— 119๊ฐ€ ์žˆ๊ณ 

tmp๊ฐ€ 119, p๊ฐ€ 11911์ธ๊ฒฝ์šฐ False๊ฐ€ ๋‚˜์˜ด

 

์ž๋ฐ”

import java.util.Arrays;

class Solution {
    public boolean solution(String[] phoneBook) {
        // 1. phoneBook์„ sortingํ•œ๋‹ค.
        Arrays.sort(phoneBook);

        // 2. 1์ค‘ Loop์„ ๋Œ๋ฉฐ ์•ž ๋ฒˆํ˜ธ๊ฐ€ ๋’ท ๋ฒˆํ˜ธ์˜ ์ ‘๋‘์–ด์ธ์ง€ ํ™•์ธํ•œ๋‹ค.
        for (int i = 0; i < phoneBook.length - 1; i++)
            if (phoneBook[i + 1].startsWith(phoneBook[i]))
                return false;
        
        // 3. ์—ฌ๊ธฐ๊นŒ์ง€ ์˜ค๋ฉด ์ ‘๋‘์–ด๊ฐ€ ์—†๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.
        return true;
    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ