algorithm

중복 문자 제거

juuuuuuun 2024. 4. 9. 14:33
6. 중복 문자 제거
설명

소문자로 된 한 개의 문자열이 입력되면 중복된 문자를 제거하고 출력하는 프로그램을 작성하세요.

중복이 제거된 문자열의 각 문자는 원래 문자열의 순서를 유지합니다.

 

입력

첫 줄에 문자열이 입력됩니다. 문자열의 길이는 100을 넘지 않는다.

 

출력

첫 줄에 중복문자가 제거된 문자열을 출력합니다.

 

예시 입력 1 

ksekkset

 

예시 출력 1

kset

 

소스 코드1

import java.util.Scanner;

public class Main {
    public static String solution(String str) {//'a' 97
        String answer="";
        int[] count = new int[26];
        char[] s = str.toCharArray();

        for (char c : s) {
            if (count[c - 97] == 0) {
                answer += c;
                count[c - 97]++;
            }
        }
        return answer;

    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        System.out.println(solution(str));
    }
}

 

소스 코드 2

import java.util.Scanner;

public class Main {
    public static String solution(String str) {
        String answer="";
        for (int i = 0; i < str.length(); i++) {
            //indexOf을 이용해 문자가 처음 나왔을 때만 answer에 저장
            if (str.indexOf(str.charAt(i)) == i) { 
                answer += str.charAt(i);
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        System.out.println(solution(str));
    }
}