대충 만든 자판

https://school.programmers.co.kr/learn/courses/30/lessons/160586

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

처음에 고민이 되었던 게 tapCountArr라는 배열을 만들고 나서 0이라는 초기값과 값 중에서 어떻게 최소값을 가져올지가 문제였다.

이후에 int.MaxValue 프로퍼티를 일치하지 않는 값에 넣어준 뒤 최소값을 뽑아내는 방식으로 해결했다.

using System;
using System.Linq;

public class Solution {
    public int[] solution(string[] keymap, string[] targets) {
        int[] answer = new int[targets.Length];
int[] tapCountArr = new int[keymap.Length];

for (int i = 0; i < targets.Length; i++)
{
    for (int j = 0; j < targets[i].Length; j++)
    {
        for(int k = 0; k < keymap.Length; k++)
        {
            int index = Array.IndexOf(keymap[k].ToCharArray(), targets[i][j]);
            if (index != -1)
            {
                tapCountArr[k] = index + 1;
            }
            else
            {
                tapCountArr[k] = int.MaxValue;
            }
        }

        int min = tapCountArr.Min();
        if (min == int.MaxValue)
        {
            answer[i] = -1;
            break;
        }
        else
        {
            answer[i] += min;
        }
    }
}
        return answer;
    }
}

 

다른 사람의 풀이

딕셔너리로 최소값이면 value 값에 넣어주는 방식도 좋은 것 같다.

using System;
using System.Collections.Generic;

public class Solution {
    public int[] solution(string[] keymap, string[] targets) 
    {
        // dictionary에 최소값으로 넣어줌
        var dict = new Dictionary<char, int>();
        for(int i = 0; i < keymap.Length; i++)
        {
            string keyStr = keymap[i];
            for(int k = 0; k < keyStr.Length; k++)
            {
                char c = keyStr[k];
                dict[c] = dict.ContainsKey(c) ? Math.Min(k, dict[c]) : k;
            }
        }

        // dictionary에서 검색 후 출력
        int[] answer = new int[targets.Length];
        for(int i = 0; i < targets.Length; i++)
        {
            string targetStr = targets[i];
            for(int k = 0; k < targetStr.Length; k++)
            {
                if(!dict.TryGetValue(targetStr[k], out int index))
                {
                    answer[i] = -1;
                    break;
                }

                answer[i] += index + 1;
            }
        }

        return answer;
    }
}

체육복

https://school.programmers.co.kr/learn/courses/30/lessons/42862

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

처음에 틀렸을 때는 배열을 정렬하지 않고 그냥 찾는 것으로 진행했다가 틀리게 되었다.

이후 배열을 정렬한 후 찾는 방식으로 해결하게 되었다.

using System;
using System.Collections.Generic;
using System.Linq;

public class Solution {
    public int solution(int n, int[] lost, int[] reserve) {
       int count = n - lost.Length;
        Array.Sort(lost);
        Array.Sort(reserve);
        
        for (int i = 0; i < lost.Length; i++)
        {
            if (reserve.Contains(lost[i]))
            {
                int index = Array.IndexOf(reserve, lost[i]);
                reserve[index] = -1;
                ++count;
            }
            else if (reserve.Contains(lost[i] - 1))
            {
                if (!lost.Contains(lost[i] - 1))
                {
                    int index = Array.IndexOf(reserve, lost[i] - 1);
                    reserve[index] = -1;
                    ++count;
                }
            }
            else if (reserve.Contains(lost[i] + 1))
            {
                if (!lost.Contains(lost[i] + 1))
                {
                    int index = Array.IndexOf(reserve, lost[i] + 1);
                    reserve[index] = -1;
                    ++count;
                }
            }
        }
        return count;
    }
}

옹알이 (2)

https://school.programmers.co.kr/learn/courses/30/lessons/133499

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

처음에 틀렸던 부분이 j = -1 이 부분인데 이전에는 j = 0으로 했다가 1부터 시작하게 되어 0을 체크하지 못해 틀리게 되었다.

이후에 j = -1로 바꾸고 나서 해결하게 되었다.

using System;

public class Solution {
    public int solution(string[] babbling) {
        int result = 0;
        string[] speech = new string[] { "aya", "ye", "woo", "ma" };
        
        for (int i = 0; i < babbling.Length; i++)
        {
            string word = babbling[i];
            string preStr = "";
            for (int j = 0; j < speech.Length; j++)
            {
                if (preStr != speech[j] && word.StartsWith(speech[j]))
                {
                    preStr = speech[j];
                    word = word.Remove(0, speech[j].Length);
                    if (word.Length == 0)
                    {
                        result++;
                        break;
                    }

                    j = -1;
                }
            }
        }
        return result;
    }
}

숫자 짝궁

https://school.programmers.co.kr/learn/courses/30/lessons/131128

 

문제 제시가 0~9까지니까 X와 Y에 배열을 10칸 만들어놓고 시작한 게 도움이 됐던 것 같다.

또한 "0000" 이렇게 나왔을 때 그냥 int로 형변환 후 다시 string으로 변환하는 작업으로 풀었는데 조건에서 길이가 300만이라고 했는데 이를 모두 int로 변환하는 작업은 오래걸리기도 하고 메모리적으로도 문제가 있다. 그래서 이전에 선언한 배열에서 0의 개수를 세는 방식으로 바꿔서 해결하게 되었다.

using System;
using System.Text;

public class Solution {
    public string solution(string X, string Y) {
        string answer = "";
        StringBuilder stringBuilder = new StringBuilder();
        int[] xArr = new int[10];
        int[] yArr = new int[10];

        for (int i = 0; i < X.Length; i++)
        {
            xArr[X[i] - '0']++;
        }

        for (int i = 0; i < Y.Length; i++)
        {
            yArr[Y[i] - '0']++;
        }


        for (int i = 0; i < xArr.Length; i++)
        {
            int min = xArr[i] > yArr[i] ? yArr[i] : xArr[i];
            for (int j = 0; j < min; j++)
            {
                stringBuilder.Append(i);
            }
        }

        if (stringBuilder.Length > 0)
        {
            char[] cArr = stringBuilder.ToString().ToCharArray();

            Array.Sort(cArr, (x, y) => -x.CompareTo(y));

            answer = new string(cArr);
            bool isOnlyZero = true;
            for (int i = 1; i < 10; i++)
            {
                if (answer.Contains(i.ToString()))
                {
                    isOnlyZero = false;
                    break;
                }
            }

            if (isOnlyZero)
            {
                answer = "0";
            }
        }
        else
        {
            answer = "-1";
        }
        
        return answer;
    }
}

로또의 최고 순위와 최저 순위

https://school.programmers.co.kr/learn/courses/30/lessons/77484

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

처음 풀었을 때는 0이 되는 경우와 아닌 경우를 나눠서 생각하지 못해 틀렸었는데

다시 문제를 보니 0아니 아니면 확정적으로 맞은 개수가 나오고 나머지 0에서 최고 최저를 가린다는 것을 알게 된 뒤 수월하게 풀 수 있었다. 특히 나는 배열로 맞춘 개수를 미리 넣어놓은 게 도움이 되었다.

using System;

public class Solution {
    public int[] solution(int[] lottos, int[] win_nums) {
            int correct = 0;
            int zeroCount = 0;

            int[] ints = new int[7] { 6, 5, 4, 3, 2, 1, 0 };

            for (int i = 0; i < lottos.Length; i++)
            {
                if (Array.Exists(win_nums, x => x == lottos[i]))
                {
                    correct++;
                }

                if (lottos[i] == 0)
                {
                    zeroCount++;
                }
            }

            // 최대 correct + zeroCount
            // 최소 correct

            int max = correct + zeroCount;
            int min = correct;

            if (max < 2)
            {
                return new int[] { 6, 6 };
            }
            else
            {
                if (min < 2)
                {
                    int maxIndex = Array.IndexOf(ints, max);
                    return new int[] { maxIndex + 1, 6 };
                }
                else
                {
                    int maxIndex = Array.IndexOf(ints, max);
                    int minIndex = Array.IndexOf(ints, min);
                    return new int[] { maxIndex + 1, minIndex + 1 };
                }
            }
    }
}

시저 암호

(int) 캐스팅을 통한 알파벳 int 값을 알아내는 것이 키 포인트인 것 같다. (소문자 97~122, 대문자 65~90)

using System;
public class Solution {
    public string solution(string s, int n) {
        char[] cArr = s.ToCharArray();
        for (int i = 0; i < cArr.Length; i++)
        {
            if (cArr[i] == ' ')
            {
                continue;
            }

            int temp = (int)cArr[i] + n;
            if (cArr[i] <= 90)
            {
                if (temp > 90)
                {
                    temp -= 26;
                }
            }
            else
            {
                if (temp > 122)
                {
                    temp -= 26;
                }
            }

            cArr[i] = (char)temp;
        }

        return new string(cArr);
    }
}

최대공약수와 최소공배수

내가 쓴 답

생각보다 너무 긴 것 같아 다른 사람 것을 찾아 봤다.

public class Solution {
    public int[] solution(int n, int m) {
        int min = 0;
        int max = 0;
        if (n < m)
        {
            return ReturnMinMax(n, m);
        }
        else
        {
            return ReturnMinMax(m, n);
        }
    }
    
    private int[] ReturnMinMax(int n, int m)
    {
        int min = 0;
        for (int i = 1; i <= n; i++)
        {
            if (n % i == 0 && m % i == 0)
            {
                min = i;
            }
        }

        int j = 1;
        int max = 0;
        while (true)
        {
            if (m * j % n == 0)
            {
                max = m * j;
                break;
            }

            j++;
        }

        return new int[] { min, max };
    }
}

 

다른 사람 풀이

a%b가 딱 떨어지면 최대 공약수인 것이고 안 나눠지면 작은 수와 큰수%작은수 한 값을 다시 재귀로 뽑아내는 것이 중요한 것 같다.

public class Solution {
    public int[] solution(int n, int m) {
        int _gcd = gcd(n, m);
        int[] answer = new int[] {_gcd, n * m / _gcd};

        return answer;
    }

    int gcd(int a, int b)
    {
        return (a % b == 0 ? b : gcd(b, a % b));
    }
}

제곱근 판별

빨리 풀다 보니 조건을 보지 않고 그냥 제곱 수를 써서 판별하다가 시간 초과가 났는데

키 포인트는 제곱근으로 판별하는 부분(newN % 1 == 0) 인 것 같다. (double 타입인 제곱근을 1로 나눴을 때 나누어 떨어지면 원래 수가 제곱 수임)

 

틀린 풀이

long answer = 0;
int i = 1;
while (i * i != n || i * i > n)
{
    i++;
}

answer = i * i > n ? -1 : (i + 1) * (i + 1);

맞은 풀이

using System;
public class Solution {
    public long solution(long n) {
        long answer = 0;
        double newN = Math.Sqrt(n);

        answer = newN % 1 == 0 ? answer = (long)Math.Pow(newN + 1, 2) : -1;
        return answer;
    }
}

 

https://school.programmers.co.kr/learn/courses/30/lessons/12934

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

char 배열 내림차순으로 정렬 후 string 변환

중요한 키 포인트는 long.Parse 부분에서 char[] arr를 new string으로 새로 할당해 주는 부분인 것 같다.

char 배열을 string으로 바꿀 때는 new string을 써야한다는 점 잊지 말자. (cArr.ToString() 이런 것 안 됨)

using System;
public class Solution {
    public long solution(long n) {
        long answer = 0;
        char[] cArr = n.ToString().ToCharArray();
        Array.Sort(cArr, (x, y) => -x.CompareTo(y));
        answer = long.Parse(new string(cArr));
        return answer;
    }
}

 

 

https://school.programmers.co.kr/learn/courses/30/lessons/12933

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

최빈값 구하기

주어진 int 배열 값 중에서 자주 나오는 값을 반환하면 되는데 이때 최빈값이 여러 개라면 -1을 반환하면 되는 문제였다.

 

나의 풀이

값들을 담는 frequentDict라는 딕셔너리를 만든 뒤

첫 for문에서 값들을 중복체크하여 딕셔너리에 담고

첫 번째 foreach문에서 max키와 value를 구한다.

두 번째 foreach문에서 최빈값이 여러 개인지 확인해 맞다면 -1을 answer에 대입한다.

Dictionary<int, int> frequentDict = new Dictionary<int, int>();
int answer = 0;

for (int i = 0; i < array.Length; i++)
{
    if (!frequentDict.ContainsKey(array[i]))
    {
        frequentDict.Add(array[i], 1);
    }
    else
    {
        frequentDict[array[i]]++;
    }
}
int max = 0;
foreach (var item in frequentDict)
{
    if (item.Value > max)
    {
        max = item.Value;
        answer = item.Key;
    }
}


foreach (var item in frequentDict)
{
    if (answer != item.Key && max == item.Value)
    {
        answer = -1;
        break;
    }
}

return answer;

 

다른 사람의 풀이

array를 n으로 그룹화하여 g.Count()를 사용해 대응되는 개수를 지정하였다.

이후 list의 cnt 기준으로 Max()를 이용하여 max인 것을 찾아 max에 넣는다.

max가 2개 이상이면 answer에 -1을 대입하고 아니면 첫번째의 n(키값)을 대입한다.

짧은 구문이지만 꽤나 이해하기 어려운 것 같다. 다시 복습해보자.

var list = array.GroupBy(x => x, g => g, (x, g) => new { n = x, cnt = g.Count() });
var max = list.Where(x => x.cnt == list.Max(o => o.cnt));
int answer = max.Count() == 1 ? max.First().n : -1;

 

https://school.programmers.co.kr/learn/courses/30/lessons/120812

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

+ Recent posts