반응형
설명
소문자로 된 한개의 문자열이 입력되면 중복된 문자를 제거하고 출력하는 프로그램을 작성하세요.
중복이 제거된 문자열의 각 문자는 원래 문자열의 순서를 유지합니다.
입력
첫 줄에 문자열이 입력됩니다. 문자열의 길이는 100을 넘지 않는다.
출력
첫 줄에 문자열이 입력됩니다. 문자열의 길이는 100을 넘지 않는다.
예시 입력 1
ksekkset
예시 출력 1
kset
StringBuilder.indexOf()으로 이용한 방법
StringBuilder로 notOverLapWord라는 변수로 중복되지 않는 단어를 선언했다.
notOverLapWord에 indexOf()로 현재 인덱스에 문자가 존재하지 않는다면 첫 번째 문자이기에 append()를 해줘서 해결했다.
package section01.E06_중복문자제거;
import java.io.*;
public class Main {
public String solution(String word){
StringBuilder notOverLapWord = new StringBuilder();
for (int i = 0; i < word.length(); i++){
String currentChar= String.valueOf(word.charAt(i));
if (notOverLapWord.indexOf(currentChar) == -1){
notOverLapWord.append(currentChar);
}
}
return notOverLapWord.toString();
}
public static void main(String[] args) throws IOException {
Main T = new Main();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String word = br.readLine();
bw.write(T.solution(word));
bw.flush();
bw.close();
}
}
String.indexOf()로 해결하는 방법
StringBuilder의 indexOf()로 해결하는 것과 별다른 차이점이 없다.
조금 다르게 해결한 점은 if (word.indexOf(word.charAt(i)) == i 현재 단어의 indexOf()로 첫 번째 index를 가져와서 반복문의 i와 동일하다면 즉, 첫 번째로 나오는 문자이면 answer에 append()를 해줬다.
Ex) ksekkset를 for문으로 반복해서 i와 charAt(i)를 비교해본다.
i와 charAt(i)가 동일하면 첫 번째 문자인 것을 볼 수 있다.
word | i | charAt(i) | i == charAt(i) |
k | 0 | 0 | true |
s | 1 | 1 | true |
e | 2 | 2 | true |
k | 3 | 0 | false |
k | 4 | 0 | false |
s | 5 | 1 | false |
e | 6 | 2 | false |
t | 7 | 7 | true |
package section01.E06_중복문자제거;
import java.io.*;
public class MainA {
public String solution(String word){
StringBuilder answer = new StringBuilder();
for (int i = 0; i < word.length(); i++){
if (word.indexOf(word.charAt(i)) == i){
answer.append(word.charAt(i));
}
}
return answer.toString();
}
}
반응형