본문 바로가기

프로그래머스/lv0

중복된 문자 제거

/* 중복된 문자 제거
 * 문자열 my_string이 매개변수로 주어집니다.
 * my_string에서 중복된 문자를 제거하고
 * 하나의 문자만 남긴 문자열을 return
 *
 * my_string            result
 * "people"             "peol"
 * "We are the world"   "We arthwold"
 *
 * "We are the world"에서 중복된 문자 "e", " ", "r" 들을 제거한
 * "We arthwold"을 return합니다.
 */

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.*;
public class programmer_0_30 {
    static String a1 = "people";
    static String a2 = "We are the world";
    public String solution(String my_string) {
        String answer = "";
        ArrayList ar = new ArrayList<>();
        
        for(int i=0; i<my_string.length(); i++){
            if(ar.indexOf(my_string.substring(i, i+1)) == -1){
                ar.add(my_string.substring(i, i+1));
                answer += my_string.substring(i, i+1);
            }   
        }        
 
        return answer;
    }
    public static void main(String args[]){
        programmer_0_30 t = new programmer_0_30();
 
        System.out.println("---------------------------------------");
        System.out.println("result = " + t.solution(a1));
        System.out.println("---------------------------------------");
        System.out.println("result2 = " + t.solution(a2));
        System.out.println("---------------------------------------");
    }
}
cs

'프로그래머스 > lv0' 카테고리의 다른 글

삼각형의 완성조건 (1)  (0) 2022.12.05
분수의 덧셈  (1) 2022.12.05
k의 개수  (0) 2022.12.05
A로 B 만들기  (0) 2022.12.05
최빈값 구하기  (1) 2022.12.05