728x90

(1) 문제

전화번호부에 적힌 전화번호 중, 한 번호가 다른 번호의 접두어인 경우가 있는지 확인하려 합니다.
전화번호가 다음과 같을 경우, 구조대 전화번호는 영석이의 전화번호의 접두사입니다.

  • 구조대 : 119
  • 박준영 : 97 674 223
  • 지영석 : 11 9552 4421

전화번호부에 적힌 전화번호를 담은 배열 phone_book 이 solution 함수의 매개변수로 주어질 때, 어떤 번호가 다른 번호의 접두어인 경우가 있으면 false를 그렇지 않으면 true를 return 하도록 solution 함수를 작성해주세요.


(2) 제한사항

  • phone_book의 길이는 1 이상 1,000,000 이하입니다.
  • 각 전화번호의 길이는 1 이상 20 이하입니다.

(3) 코드

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

using namespace std;
bool comp(string a, string b);
bool solution(vector<string> phone_book) {
    bool answer = true;

    sort(phone_book.begin(), phone_book.end(), comp);

    for (int i = 0; i < phone_book.size(); i++)
    {
        for (int j = i + 1; j < phone_book.size(); j++)
        {
            if (phone_book[i] == phone_book[j].substr(0, phone_book[i].size()))
            {
                answer = false;
                return answer;
            }
        }
    }

    return answer;
}

bool comp(string a, string b)
{
    if (a.length() < b.length())
    {
        return true;
    }
    else if (a.length() == b.length())
    {
        return a < b;
    }
    else
        return false;
}

(4) 실행결과


반응형

+ Recent posts