-
[프로그래머스, Lv1] 숫자 짝꿍알고리즘 문제/Java 2024. 8. 27. 15:12
코딩테스트 연습 - 숫자 짝꿍 | 프로그래머스 스쿨 (programmers.co.kr)
문제설명
두 정수 X, Y의 임의의 자리에서 공통으로 나타나는 정수 k(0 ≤ k ≤ 9)들을 이용하여 만들 수 있는 가장 큰 정수를 두 수의 짝꿍이라 합니다(단, 공통으로 나타나는 정수 중 서로 짝지을 수 있는 숫자만 사용합니다). X, Y의 짝꿍이 존재하지 않으면, 짝꿍은 -1입니다. X, Y의 짝꿍이 0으로만 구성되어 있다면, 짝꿍은 0입니다.
예를 들어, X = 3403이고 Y = 13203이라면, X와 Y의 짝꿍은 X와 Y에서 공통으로 나타나는 3, 0, 3으로 만들 수 있는 가장 큰 정수인 330입니다. 다른 예시로 X = 5525이고 Y = 1255이면 X와 Y의 짝꿍은 X와 Y에서 공통으로 나타나는 2, 5, 5로 만들 수 있는 가장 큰 정수인 552입니다(X에는 5가 3개, Y에는 5가 2개 나타나므로 남는 5 한 개는 짝 지을 수 없습니다.)
두 정수 X, Y가 주어졌을 때, X, Y의 짝꿍을 return하는 solution 함수를 완성해주세요.제한사항
- 1 ≤ wallpaper의 길이 ≤ 50
- 1 ≤ wallpaper[i]의 길이 ≤ 50
- wallpaper의 모든 원소의 길이는 동일합니다.
- wallpaper[i][j]는 바탕화면에서 i + 1행 j + 1열에 해당하는 칸의 상태를 나타냅니다.
- wallpaper[i][j]는 "#" 또는 "."의 값만 가집니다.
- 바탕화면에는 적어도 하나의 파일이 있습니다.
- 드래그 시작점 (lux, luy)와 끝점 (rdx, rdy)는 lux < rdx, luy < rdy를 만족해야 합니다.
접근 방법
문제 자체는 한 번에 드래그 하기 위해선
X 최소 위치 ~ X 최대 위치, Y 최소 위치 ~ Y 최대 위치의 범위로 둘러싸면 되기에 Min Max의 형태로 단순했지만,
내가 생각한 X, Y개념과 이미지의 X, Y개념이 서로 달라 어려움을 겪었다.
문제 풀이는 for문을 통해 wallpaper를 순차적으로 순회했고,
다시 wallpaper[i]을 for문을 통해 순회하며 charAt 결과가 '#'인 경우,
x 최소 위치, y 최소 위치, x 최대 위치, y 최대 위치를 갱신하게 했다.
최종 코드
더보기import java.util.Arrays; class Solution { public String solution(String X, String Y) { String answer = ""; StringBuilder str = new StringBuilder(); StringBuilder str2 = new StringBuilder(); int xIndex = 0, yIndex = 0; char[] xChars = X.toCharArray(); char[] yChars = Y.toCharArray(); Arrays.sort(xChars); Arrays.sort(yChars); while(xIndex < X.length() && yIndex < Y.length()) { if(xChars[xIndex] == yChars[yIndex]) { str2.append(xChars[xIndex]); ++xIndex; ++yIndex; } else if (xChars[xIndex] > yChars[yIndex]) { ++yIndex; } else { ++xIndex; } } if(str2.length() == 0) { return "-1"; } char[] resultArray = str2.toString().toCharArray(); if(resultArray[resultArray.length - 1] == '0') { return "0"; } answer = ""; for(int i = resultArray.length - 1; i >= 0; --i) { str.append(resultArray[i]); } return str.toString(); } }
'알고리즘 문제 > Java' 카테고리의 다른 글
[프로그래머스, Lv1] 푸드 파이터 대회 (0) 2024.08.30 [프로그래머스, Lv1] 둘만의 암호 (0) 2024.08.26 [프로그래머스, Lv1] 성격 유형 검사하기 (0) 2024.08.23 [프로그래머스, Lv1] 개인정보 수집 유효기간 (0) 2024.08.21 [프로그래머스, Lv1] 바탕화면 정리 (0) 2024.08.20