Java : 전화번호 목록 (해시 알고리즘)

keymu·2024년 9월 24일
0
  1. StringBuilder 이용 (정답률 60%)
import java.util.Arrays;
class Solution {
    public boolean solution(String[] phone_book) {
        boolean answer = true; 
        StringBuilder phone=new StringBuilder();
        for(int i=0;i<phone_book.length;i++){
            phone.append(phone_book[i]);
        }
        for(int i=0;i<phone_book.length;i++){
            String stringToRemove = phone_book[i];
            int startIndex = phone.indexOf(stringToRemove);
            int endIndex = startIndex + stringToRemove.length();
            String phone_deleted=(phone.delete(startIndex, endIndex)).toString();
            if (phone_deleted.contains(phone_book[i])){
                answer=false;
                break;
            }
        }
        return answer;
    }
}
  1. Sorting
import java.util.Arrays;
class Solution {
    public boolean solution(String[] phone_book) {
        // Step 1: Sort the phone book
        Arrays.sort(phone_book);
        // Step 2: Check each phone number with the next one
        for (int i = 0; i < phone_book.length - 1; i++) {
            // Check if the current number is a prefix of the next number
            if (phone_book[i + 1].startsWith(phone_book[i])) {
                return false; // Found a prefix
            }
        }
        return true; // No prefixes found
    }
}
  1. Hash
import java.util.HashSet;
class Solution {
    public boolean solution(String[] phone_book) {
        HashSet<String> set = new HashSet<>();
        for (String phone : phone_book) {
            set.add(phone);
        }
        for (String phone : phone_book) {
            for (int i = 1; i <= phone.length(); i++) {
                if (set.contains(phone.substring(0, i)) && !phone.substring(0, i).equals(phone)) {
                    return false;
                }
            }
        }
        return true;
    }
}
profile
Junior Backend Developer

0개의 댓글