한 걸음 두 걸음

백준 11723 집합 ] HashSet Collection 사용 본문

CSE/baekjoon & swexpert

백준 11723 집합 ] HashSet Collection 사용

언제나 변함없이 2019. 4. 13. 21:41
반응형
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.*;
public class Main {

	public static void main(String[] args)  throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder("");
		
		int testCase =  Integer.parseInt(br.readLine());

		Set<String> hs1 = new HashSet<>();
		
		for(int i = 0 ; i < testCase; i++) {
			
			StringTokenizer st = new StringTokenizer(br.readLine());

			switch(st.nextToken()) {
			case "add":
				hs1.add(st.nextToken());
				break;
			case "remove":
				hs1.remove(st.nextToken());
				break;
			case "check":
				if( hs1.contains(st.nextToken())) sb.append("1 ");
				else sb.append("0 ");
				break;
			case "toggle":
				String toggleStr = st.nextToken();
				if(hs1.contains(toggleStr)) hs1.remove(toggleStr);
				else hs1.add(toggleStr);
				break;
			case "all":
				hs1.clear();
				for(int j = 1 ; j <= 20; j++)
					hs1.add(j+"");
				break;
			case "empty":
				hs1.clear();
				break;
			}
		}

		System.out.println(sb.toString());
	}
}

 

 

 

참고 > 시간초과 났던 코드

import java.util.*;
public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int testCase = sc.nextInt();
        sc.nextLine();
        HashSet<String> hs1 = new HashSet<>();
        HashSet<String> allSet = new HashSet<>();
        for(int i = 1 ; i <= 20; i++)
            allSet.add(i+"");

        for(int i = 0 ; i < testCase; i++) {
            String str = sc.next();
            switch(str) {
            case "add":
                hs1.add(sc.next());
                break;
            case "remove":
                hs1.remove(sc.next());
                break;
            case "check":
                if( hs1.contains(sc.next())) System.out.println("1");
                else System.out.println("0");
                break;
            case "toggle":
                String toggleStr = sc.next();
                if(hs1.contains(toggleStr)) hs1.remove(toggleStr);
                else hs1.add(toggleStr);
                break;
            case "all":
                hs1.clear();
                hs1 = (HashSet)allSet.clone();
                break;
            case "empty":
                hs1.clear();
                break;
            }
        }

    }
}

 

반응형