https://www.acmicpc.net/problem/11723
11723번: 집합
첫째 줄에 수행해야 하는 연산의 수 M (1 ≤ M ≤ 3,000,000)이 주어진다. 둘째 줄부터 M개의 줄에 수행해야 하는 연산이 한 줄에 하나씩 주어진다.
www.acmicpc.net
add, remove 등 메소드를 직접 구현해도 되지만, 자료구조를 이용해서 푸는 게 훨씬 좋아보인다. 메소드별로 조건을 자세히보면 집합 S 내 특정원소의 존재여부만 체크하면 되는 조건들로 이루어져 있으므로 선형구조보다는 Set이나 Map 등을 이용해서 해결하는 것이 효율적이라고 생각했고, 나는 HashSet을 이용해서 간단하게 문제를 해결할 수 있었다.
문제 및 입출력
코드
import java.util.HashSet;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
HashSet<String> set = new HashSet<String>();
StringBuilder sb = new StringBuilder();
int m = sc.nextInt();
String temp = sc.nextLine();
for(int i=0; i<m; i++)
{
String[] input = sc.nextLine().split(" ");
if(input[0].equals("add"))
{
set.add(input[1] + "");
}
else if(input[0].equals("remove"))
{
if(set.contains(input[1]))
{
set.remove(input[1]);
}
}
else if(input[0].equals("check"))
{
if(set.contains(input[1]))
{
sb.append("1" + "\n");
}
else
{
sb.append("0" + "\n");
}
}
else if(input[0].equals("toggle"))
{
if(set.contains(input[1]))
{
set.remove(input[1]);
}
else
{
set.add(input[1]);
}
}
else if(input[0].equals("all"))
{
set.clear();
for(int j=1; j<=20; j++)
{
set.add(j + "");
}
}
else if(input[0].equals("empty"))
{
set.clear();
}
}
System.out.println(sb.toString());
sc.close();
}
}
'[ 다먹살 ] > - Coding' 카테고리의 다른 글
[프로그래머스] 레벨2 호텔 대실 (6) | 2023.02.28 |
---|---|
[프로그래머스] 레벨2 마법의 엘리베이터 (0) | 2023.02.28 |
[프로그래머스] 레벨1 카드 뭉치 (0) | 2023.02.23 |
[백준] 1731 추론 (0) | 2023.02.23 |
[백준] 2563 색종이 (0) | 2023.02.22 |
댓글