ABOUT ME

Today
Yesterday
Total
  • [LeetCode] 1694. Reformat Phone Number
    알고리즘 문제 풀이 2021. 5. 27. 12:31

    문제 출처: https://leetcode.com/problems/reformat-phone-number/

     

    Reformat Phone Number - LeetCode

    Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

    leetcode.com

    문제

    핸드폰 번호가 문자열 number로 주어진다. number는 숫자, 공백 ' '. 그리고/또는 대시 '-'로 구성된다.

     

    주어진 number를 특정 형태로 재구성하려고 한다. 첫째, 모든 공백과 대시를 제거한다. 그리고, 왼쪽에서 오른쪽으로 4개 이하의 숫자가 남을 때까지 3개씩 그룹화한다. 마지막 숫자는 다음의 규칙을 따라 그룹화한다:

    • 2개: 길이 2의 단일 블록으로 그룹화
    • 3개: 길이 3의 단일 블록으로 그룹화
    • 4개: 길이가 2인 두개 블록으로 그룹화

     

    블록들은 대시로 합쳐진다. 재구조화 과정은 길이가 1인 블록은 만들지 않으며, 길이가 2인 블록은 최대 2개까지 생성할 수 있다.

     

    재구조화 후 핸드폰 번호 를 반환하라.

    예제

    Input: number = "1-23-45 6"
    Output: "123-456"
    
    Explanation: The digits are "123456".
    Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123".
    Step 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is "456".
    Joining the blocks gives "123-456".
    Input: number = "123 4-567"
    Output: "123-45-67"
    
    Explanation: The digits are "1234567".
    Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123".
    Step 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are "45" and "67".
    Joining the blocks gives "123-45-67".

    풀이

    1차적으로 주어진 문자열에 대해서 공백과 대시를 제거하는 작업을 수행해야 한다.

     

    언어에서 제공해주는 문자열 치환 함수를 사용 혹은 for문을 통한 탐색을 통한 제거 방법이 존재한다.

    
    // JavaScript의 replace()사용
    number.replace(/[' '-]/g, '');
    
    // for문 탐색
    refined_number = '';
    for (let ch of number) {
        if (ch == ' ' || ch == '-') { continue; }
        refined_number += ch;
    }
    

    처음 주어진 문자열에서 그룹화하는데 불필요한 문자를 제거한 후, 본격적인 그룹화 작업에 들어가는데,

     

    3개씩 묶어 나가면 결국 마지막에 남는 숫자의 수는 0, 1, 2개가 된다. 각각에 대한 처리 방법을 생각해보아야 한다.

     

    0 또는 2개가 남은 경우, 별다른 처리 없이 하나의 블록으로 처리하는 것으로 문제의 모든 조건은 만족시킬 수 있다.

     

    문제는 1개가 남은 경우이다. 길이가 1인 블록은 만들지 않는다는 조건이 있으므로, 바로 앞 블록을 활용해서 이 문제를 해결할 수 있다. 앞 블록의 마지막 숫자를 분리해서 1개 남은 숫자와 결합하는 것이다.

    number = "1234567"
    
    - 숫자를 3개씩 분리
    1 block = 123
    2 block = 456
    3 block = 7   => 길이가 1인 블록은 만들면 안됨, 2블록에서 숫자 하나를 빌려옴
    
    - 1개 남은 블록에 대한 조치 후 블록
    1 block = 123
    2 block = 45
    3 block = 67

    이 과정을 코드로 작성하면 다음과 같다.

    
    let ans = '';
    
    // 왼쪽에서부터 3개씩 묶는 과정
    const val = Math.trunc(N / 3);
    let index = -1;
    for (let i = 0; i < val; i++) {
        ans += arr_nums[index+1] + arr_nums[index+2] + arr_nums[index+3] + '-';
        index += 3;
    }
    
    // 남는 숫자 수에 따른 조치
    let i = index+1;
    if (N % 3 == 0) { ans = ans.slice(0, ans.length-1); }
    else if (N % 3 == 1) {
        ans = ans.slice(0, ans.length-2) + '-';
        i = N-2;
    }
    for (; i < N; i++) {
        ans += arr_nums[i];
    }
    

    Github: 1694.js

     

    opwe37/Algorithm-Study

    Contribute to opwe37/Algorithm-Study development by creating an account on GitHub.

    github.com

     

    '알고리즘 문제 풀이' 카테고리의 다른 글

    댓글

Designed by Tistory.