반응형
SMALL

# 해결
str.indexOf(문자) : 문자가 처음 등장한 위치(int)리턴
str.charAt(인덱스번호): 해당 인덱스의 문자(char) 리턴
System.out.println(str.charAt(i) + “ “+ i + “ “+ str.indexOf(str.charAt(i))) 를 먼저 해보면, 아래와 같은 결과가 나타난다.
즉, 처음으로 그 문자가 등장한 위치와 그 문자의 인덱스 번호가 같으면, 아직 중복되지 않았다는 뜻이므로 출력하면 된다.
만약 다르다면, 그 문자가 이미 전에 나왔다는 뜻이므로, 중복되었다는 뜻이다.

import java.util.Scanner;
public class Main {
public String solution(String str){
String answer = "";
for(int i=0;i<str.length();i++){
// 처음으로 그 문자가 등장한 위치와 해당 문자의 인덱스 번호가 다르면 중복!
// 같으면 중복이 아니므로 출력!
if(str.indexOf(str.charAt(i))==i) answer += str.charAt(i);
}
return answer;
}
public static void main(String[] args){
Main T = new Main();
Scanner kb =new Scanner(System.in);
String str = kb.next();
System.out.println(T.solution(str));
}
}
반응형
LIST
'자바 알고리즘' 카테고리의 다른 글
08. 팰린드롬 (replaceAll 정규식 이용) (0) | 2022.04.11 |
---|---|
07. 회문 문자열 (0) | 2022.04.08 |
05. 특정 문자 뒤집기 (0) | 2022.04.08 |
04. 단어 뒤집기 (0) | 2022.04.06 |
03. 문장 속 단어 (0) | 2022.04.06 |
댓글