Java/프로그래머스
[Java] 프로그래머스 [TEST] Anagram
SeungyubLee
2022. 11. 28. 15:58
import java.util.*;
public class Solution {
// 애너그램 관계
public static int solution(int[] arr) {
int answer = 0;
String tempStr = "";
HashSet<String> hs = new HashSet<>(); // HashSet 사용
// HashMap<String, Integer> hm = new HashMap<>(); // HashMap 사용
for (int i = 0; i < arr.length; i++) {
char[] charArr = Integer.toString(arr[i]).toCharArray();
Arrays.sort(charArr); // 오름차순 정렬
tempStr = new String(charArr); // 문자열 생성
if (!hs.contains(tempStr)) {
hs.add(tempStr);
answer++;
}
// if (!hm.containsKey(tempStr)) {
// hm.put(tempStr, 1); // Integer 자리의 경우 1이 아니어도 됨
// answer++;
// }
}
return answer;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {112, 1814, 121, 1481, 1184, 512, 125, 521, 80}; // 단, 자리수는 같아야 함
System.out.println(solution(arr)); // 4 // {112, 121}, {1814, 1481, 1184}, {512, 125, 521}, {80} // 4개의 그룹
}
}
프로그래머스 애너그램 문제 풀이 Java