프로그래머스 - 한 번만 등장한 문자

박상준·2023년 6월 26일
0

코딩테스트 연습

목록 보기
4/7

Solution

import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;

//한 번만 등장한 문자
public class Programmers01 {
    public static String solution(String s) {
        String answer = "";
        int idx = 0;
        Hashtable<Integer, String> ht = new Hashtable<>();
        ArrayList<String> result = new ArrayList<>();

        for (String item : s.split("")) {
            ht.put(idx++, item);
        }

        for (int i = 0; i < ht.size(); i++) {
            int cnt = 0;
            for (int j = 0; j < ht.size(); j++) {
                if (ht.get(i).equals(ht.get(j))) {
                    cnt++;
                }
            }
            if (cnt == 1) {
               result.add(ht.get(i));
            }
        }

        Collections.sort(result);
        for (String item : result) {
            answer += item;
        }
        return answer;
    }

    public static void main(String[] args) {
        String s = "hello";
        System.out.println(solution(s));
    }
}

사실 Hashtable이 아니라 HashMap이나 아니면 다른 더 쉬운 방법도 존재하나 최근에 Hashtable을 공부했기 때문에 Hashtable로 풀어봤다.
Hashtable에 키값과 함께 문자열을 split해서 넣어주었고 이중포문을 돌며 중복되는 문자가 있는지 확인한 뒤 중복문자가 아니면 result에 넣어주고 result를 sort해서 리턴해주면 된다.

profile
신입 개발자를 꿈꾸는 코린이

0개의 댓글