6. 중복문자제거
소문자로 된 한개의 문자열이 입력되면 중복된 문자를 제거하고 출력하는 프로그램을 작성하세요.
중복이 제거된 문자열의 각 문자는 원래 문자열의 순서를 유지합니다.
첫 줄에 문자열이 입력됩니다. 문자열의 길이는 100을 넘지 않는다.
첫 줄에 중복문자가 제거된 문자열을 출력합니다.
===================================================
charAt(x)를 이용하여 특정위치에 있는 문자를 찾아내고 이 문자를 indexOf( )에 넣어 이 특정문자가 처음 나오는 위치를 알아낸다. 만약 처음 나오는 문자와 현재의 위치가 같다면 answer에 추가한다. 그렇지 않으면 중복되어서 나오는 것이므로 추가하지 않는다. 마지막으로 답을 반환한다.
import java.util.Scanner;
public class Main {
public String solution(String sentence) {
String answer="";
for(int i=0;i<sentence.length();i++) {
if(sentence.indexOf(sentence.charAt(i))==i)
answer+=sentence.charAt(i);
}
return answer;
}
public static void main(String[] args) {
Main main = new Main();
Scanner scan = new Scanner(System.in);
String sentence=scan.next();
System.out.println(main.solution(sentence));
}
}
1) 특정 위치에 있는 문자
2) 특정문자가 처음 나오는 위치