문제
PROGRAMMERS-962 행성에 불시착한 우주비행사 머쓱이는 외계행성의 언어를 공부하려고 합니다. 알파벳이 담긴 배열 spell과 외계어 사전 dic이 매개변수로 주어집니다. spell에 담긴 알파벳을 한번씩만 모두 사용한 단어가 dic에 존재한다면 1, 존재하지 않는다면 2를 return하도록 solution 함수를 완성해주세요.
입출력 예
spell | dic | result |
["p", "o", "s"] | ["sod", "eocd", "qixm", "adio", "soo"] | 2 |
["z", "d", "x"] | ["def", "dww", "dzx", "loveaw"] | 1 |
["s", "o", "m", "d"] | ["moos", "dzx", "smm", "sunmmo", "som"] | 2 |
1. spell[] 정렬하기
Arrays.sort(spell);
2. spell[]을 새로운 String(newString)으로 만들어주기
String newSpell = "";
for(int i=0; i<spell.length; i++){
newSpell += spell[i];
}
3. dic[i] 원소 정렬하기
for(int i=0; i<dic.length; i++){
char[] dicChar = dic[i].toCharArray();
Arrays.sort(dicChar);
String sortedDicChar = new String(dicChar);
...
"sod" → "dos"
로 정렬시키고자했습니다.
dic[i] 원소 하나하나를 정렬하기 위해 Arrays.sort()를 사용하려면
먼저 dic[i]를 Array로 만들어줘야합니다.
그래서 toCharArray()를 사용해 dicChar라는 char형의 배열을 만들어주었습니다.
그리고 정렬된 dicChar를 활용해 새로운 sortedDicChar라는 문자열로 만들어줍니다.
만약 sortedDicChar가 newSpell과 같다면
answer를 1로 저장하고
반복문을 종료합니다.
4. 정렬된 dic[i]와 newString이 같은지 비교하기
...
if(sortedDicChar.equals(newSpell)){
answer = 1;
break;
}
}
코드
import java.util.*;
class Solution {
public int solution(String[] spell, String[] dic) {
int answer = 2;
int result = 0;
Arrays.sort(spell);
String newSpell = "";
for(int i=0; i<spell.length; i++){
newSpell += spell[i];
}
for(int i=0; i<dic.length; i++){
char[] dicChar = dic[i].toCharArray();
Arrays.sort(dicChar);
String sortedDicChar = new String(dicChar);
if(sortedDicChar.equals(newSpell)){
answer = 1;
break;
}
}
return answer;
}
}
제가 작성한 코드는 아래에서 확인하실 수 있습니다.
https://github.com/eonwy/programmers
GitHub - eonwy/programmers: 🔎 coding-test (programmers) 🔍
🔎 coding-test (programmers) 🔍. Contribute to eonwy/programmers development by creating an account on GitHub.
github.com
'🫧 코테 : CodingTest' 카테고리의 다른 글
[프로그래머스] Java : 겹치는 선분의 길이 (0) | 2024.04.11 |
---|---|
[프로그래머스] Java : 평행 (1) | 2024.04.11 |
[프로그래머스] Java : 안전지대 (0) | 2024.04.02 |
[프로그래머스] Java : 다항식 더하기 (0) | 2024.04.02 |
[프로그래머스] Java : 직사각형 넓이 구하기 (0) | 2024.04.01 |