๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/์•Œ๊ณ ๋ฆฌ์ฆ˜

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/JAVA] ์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก - ํ•ด์‹œ

by ynzu๐Ÿค 2022. 2. 18.
๋ฐ˜์‘ํ˜•

 

 

๋จผ์ € ๋ฐฐ์—ด์˜ ๋ฐ์ดํ„ฐ ํ•˜๋‚˜ํ•˜๋‚˜๋ฅผ ๋‹ค ๋น„๊ตํ•˜๋Š” ๋‹จ์ˆœํ•œ ๋ฐฉ๋ฒ•์œผ๋กœ ํ’€์–ด๋ณด์•˜๋‹ค.  ์—ญ์‹œ๋‚˜ ํšจ์œจ์„ฑ ํ…Œ์ŠคํŠธ์—์„œ ํƒˆ๋ฝ!  ์ด๋ ‡๊ฒŒ ํ’€์ง€ ๋ง๋ผ๊ณ   ๊ธฐ๋กํ•ด๋ณธ๋‹ค..

class Solution {
    public boolean solution(String[] phone_book) {
        boolean answer = true;
        
         for(int i=0; i<phone_book.length; i++) {
        	for(int j=0; j<phone_book.length; j++) {
        		if(i!=j) {
        			if(phone_book[i].startsWith(phone_book[j])) {
        				answer = false;
        				break;
        			}
        			
        		}
        	}
        }
        
        
        return answer;
    }
}

 

import java.util.Arrays;

class Solution {
   public boolean solution(String[] phone_book) {
        boolean answer = true;
        
        Arrays.sort(phone_book);
        
         for(int i=0; i<phone_book.length-1; i++) {
        	for(int j=i+1; j<phone_book.length; j++) {
				if(phone_book[j].startsWith(phone_book[i])) {
					answer = false;
					return answer;
				}
        	}
        }
        
        
        return answer;
    }
}

๋จผ์ € phone_book์„ sortingํ–ˆ๋Š”๋ฐ๋„ ๋˜ ํšจ์œจ์„ฑ ํ…Œ์ŠคํŠธ 3, 4์—์„œ ๊ฑธ๋ ค๋ฒ„๋ฆฌ๊ณ  ๋ง์•˜๋‹ค.

hash๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๋จผ์ € ํ’€์–ด๋ณด๊ณ  ์‹ถ์—ˆ๋Š”๋ฐ.. hash๋กœ ํ’€์–ด์•ผํ•˜๋‚˜ ๋ณด๋‹ค.

 

import java.util.HashMap;

class Solution2 {
    public boolean solution(String[] phone_book) {
        boolean answer = true;
        
        HashMap<String,Integer> hm = new HashMap<String, Integer>();
        for (int i=0; i<phone_book.length; i++) {
        	hm.put(phone_book[i], i);
        }
        
        for(int i=0; i<phone_book.length; i++) {
        	for(int j=0; j<phone_book[i].length(); j++) {
        		String str = phone_book[i].substring(0,j);
        		if (hm.containsKey(str)) {
        			return false;
                }
        	}
        }
        
        
        return answer;
    }
}

 HashMap์—  ์ „ํ™”๋ฒˆํ˜ธ๋ฅผ putํ•˜๊ณ , ๊ฐ ์ „ํ™”๋ฒˆํ˜ธ๋ฅผ ์ „ํ™”๋ฒˆํ˜ธ ๊ธธ์ด๊นŒ์ง€ ํ•˜๋‚˜์”ฉ ์ฆ๊ฐ€์‹œํ‚ค๋ฉด์„œ ์ž˜๋ž์„ ๋•Œ ๊ทธ ๊ฐ’์„ ํ‚ค๋กœ ๊ฐ€์ง€๋Š”๊ฒƒ์ด HashMap์— ์žˆ์œผ๋ฉด false๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. ์—†์œผ๋ฉด true ์ถœ๋ ฅ!

 

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€