Ottoman

프로그래머스 Lv1 숫자 짝꿍 본문

코테풀기

프로그래머스 Lv1 숫자 짝꿍

오토만 2024. 12. 26. 22:24

코딩테스트 연습 - 숫자 짝꿍 | 프로그래머스 스쿨

 

계획 수립 :

매개변수 X, Y 에게 존재하는 숫자와 그 숫자가 몇 개인지 정리한다.

int[]를 이용해 인덱스에 숫자를 매칭시켜서 저장한다.

 

겹치는 숫자가 없다면 "-1"을 반환한다.

겹치는 숫자가 있다면 두 개의 int[]값에서 작은 값을 겹치는 갯수로 한다.

 

StringBuilder를 이용해 높은 인덱스(9)부터 값만큼 인덱스숫자를 추가한다.

 

 

 

첫 제출

using System;
using System.Text;

public class Solution
{
    public string solution(string X, string Y)
    {
        StringBuilder sb = new StringBuilder();

        char[] xchars = X.ToCharArray();
        char[] ychars = Y.ToCharArray();
        int[] xIndex = CountChars(xchars);
        int[] yIndex = CountChars(ychars);
        int[] overlapIndex = new int[10];

        for (int i = 0; i < 10; ++i)
        {
            if (xIndex[i] != 0 && yIndex[i] != 0)
            {
                int min = Math.Min(xIndex[i], yIndex[i]);
                overlapIndex[i] = min;
            }
        }

        for (int i = overlapIndex.Length - 1; i > 0; i--)
        {
            if (overlapIndex[i] != 0)
            {
                for (int j = 0; j < overlapIndex[i]; j++)
                {
                    sb.Append(i);
                }
            }
        }

        if (sb.Length == 0)
        {
            return "-1";
        }
        else if (int.Parse(sb.ToString()) == 0)
        {
            return "0";
        }
        
        return sb.ToString();
    }

    int[] CountChars(char[] chars)
    {
        int[] index = new int[10];
        foreach (var item in chars)
        {
            if (item == '0') index[0]++;
            else if (item == '1') index[1]++;
            else if (item == '2') index[2]++;
            else if (item == '3') index[3]++;
            else if (item == '4') index[4]++;
            else if (item == '5') index[5]++;
            else if (item == '6') index[6]++;
            else if (item == '7') index[7]++;
            else if (item == '8') index[8]++;
            else if (item == '9') index[9]++;
        }
        return index;
    }
}

 

몇 가지 테스트케이스는 통과했지만 제한사항의 3백만 '자릿수'를 해결하지 못했다.

게다가 이 문제에서는 BigInteger를 사용하지 못한다.


 

using System;
using System.Text;

public class Solution
{
    public string solution(string X, string Y)
    {
        StringBuilder sb = new StringBuilder();
        bool isOnlyzero = true;

        int[] countX = new int[10];
        int[] countY = new int[10];

        foreach (char c in X)
        {
            countX[c - '0']++;
        }
        foreach (char c in Y) countY[c - '0']++;

        for(int i = 9; i >=0; i--)
        {
            int common = Math.Min(countX[i], countY[i]);
            if( common > 0 )
            {
                if( i != 0) isOnlyzero = false;
                sb.Append(new string((char)(i + '0'), common));
            }
        }

        if( sb.Length == 0 )
        {
            return "-1";
        }
        if (isOnlyzero)
        {
            return "0";
        }
        return sb.ToString();
    }
}

 

문자열은 자릿수에 제한이 없다.

 

여기서 사용된 테크닉

1. countX[c - '0']++;

char형의 c가 숫자의 문자일 때 문자'0'을 빼면 숫자의 int값을 얻을 수 있다.

c가 숫자 '2'라면 int값 50을 가지고 '0'은 int값 48을 가진다. 50 - 48 = 2

 

2. sb.Append(new string((char)(i + '0'), common));

// 요약: Initializes a new instance of the System.String class to the value indicated by a specified Unicode character repeated a specified number of times.
// 매개 변수:
// c:  A Unicode character. //
// count: The number of times c occurs. //
// 예외:
// T:System.ArgumentOutOfRangeException: count is less than zero.
public String(char c, int count);

 

string이 제공하는 생성자다. char형 c를 count만큼 반복하는 새로운 문자열을 만든다.

c = '3', count가 5라면 "33333"이라는 string이 만들어진다.

 


매우 큰 '자릿수'를 요구하면서 BigInteger를 이용하지 못하는 경우에 대응할 수 있는지와 문자, 문자열을 알고 있는지 묻는 문제같았다.

 

'코테풀기' 카테고리의 다른 글

프로그래머스 Lv2 요격 시스템  (0) 2024.12.26
백준 11050번 : 이항 계수  (1) 2024.12.01
백준 10816번 : 정렬과 이진탐색  (1) 2024.11.17
백준 13023번  (0) 2024.11.08
백준 16929번  (0) 2024.11.06