[프로그래머스/Java] Lv.0 중복된 문자 제거

febCho·2024년 4월 17일
0

코딩테스트

목록 보기
175/253
post-thumbnail

문제

문자열 my_string이 매개변수로 주어집니다. my_string에서 중복된 문자를 제거하고 하나의 문자만 남긴 문자열을 return하도록 solution 함수를 완성해주세요.

- 제한사항

  • 1 ≤ my_string ≤ 110
  • my_string은 대문자, 소문자, 공백으로 구성되어 있습니다.
  • 대문자와 소문자를 구분합니다.
  • 공백(" ")도 하나의 문자로 구분합니다.
  • 중복된 문자 중 가장 앞에 있는 문자를 남깁니다.

풀이

중복을 허용하지 않는 특징을 가지고 있는 HashSet을 이용해 중복 체크를 해준 다음 메모리/시간 효율을 위해 StringBuffer 객체에 담아 toString()으로 반환 타입에 맞게 반환해 주었다.

import java.util.HashSet;

class Solution {
    public String solution(String my_string) {
        HashSet<Character> set = new HashSet<>();
        StringBuffer answer = new StringBuffer();

        for (char c : my_string.toCharArray()) {
            if (!set.contains(c)) {
                set.add(c);
                answer.append(c);
            }
        }

        return answer.toString();
    }
}

결과

profile
Done is better than perfect.

0개의 댓글