Programmers 코딩테스트 고득점 Kit - 해시(Hash) 전화번호 목록 C++

박준용·2022년 2월 26일
0
post-thumbnail

문제


풀이 1 - hash를 사용하지 않은 풀이

문제를 처음 봤을 때 hash 보다는 문자열로 접근하는 것이 더 효율적이어 보였다.
문자열을 정렬해서 옆에 것과 비교하면 되겠다고 생각했다.
바로 옆의 문자열을 substr를 사용해 비교했다.

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

bool solution(vector<string> phone_book) {
    bool answer = true;
    sort(phone_book.begin(),phone_book.end());
    for(int i = 0; i < phone_book.size()-1; i++){
        if(phone_book[i] == phone_book[i+1].substr(0,phone_book[i].size())){
            answer = false;
        }
    }
    return answer;
}

풀이 2 - hash를 사용한 풀이

어떻게 hash를 이용해야 고민하다가 해쉬에 저장해두고 부분문자열을 비교해봤다.
hash에 저장된 값과 부분 문자열이 같을 때 false로 반환했다.

#include <string>
#include <vector>
#include <algorithm>
#include <map>

using namespace std;

bool solution(vector<string> phone_book) {
    bool answer = true;
    map<string, bool> map;
    for(int i=0; i<phone_book.size(); i++){
        map[phone_book[i]] = true;
    }
    for(int i=0; i<phone_book.size(); i++){
        string num="";
        for(int j=0; j<phone_book[i].size(); j++){
            num += phone_book[i][j];
            if(map[num] && num!=phone_book[i]){
                answer = false;
            }
        }
    }
    return answer;
}

profile
경험을 좋아하는 개발자 박준용입니다.

0개의 댓글