IT/프로그래머스
프로그래머스 중복된 문자 제거 - Java
짐99
2023. 6. 1. 14:16
반응형
문제설명
문자열 my_string이 매개변수로 주어집니다. my_string에서 중복된 문자를 제거하고 하나의 문자만 남긴 문자열을 return하도록 solution 함수를 완성해주세요.
제한사항
1<=my_string<=10
my_string은 대문자, 소문자, 공백으로 구성되어 있습니다.
대문자와 소문자를 구분합니다.
공백(" ")도 하나의 문자로 구분합니다.
중복된 문자 중 가장 앞에 있는 문자를 남깁니다.
입출력 예
1. "people"에서 중복된 문자 "p"와 "e"를 제거한 "peol"을 return합니다.
2. "We are the world"에서 중복된 문자 "e", " ", "r"들을 제거한 "We arthwold"을 return합니다.
풀이
my_string 문자열을 배열로 옮긴 후, 반복문을 돌리고 equals를 통해 중복된 문자를 제거한다.
String.join
문자열을 붙여주는 메서드이다.
String.join(구분자, 어레이나 컬렉션 형태)
(java 버전 8에서만 사용 가능함)
코드
class Solution {
public String solution(String my_string) {
String answer = "";
String[] index = new String[my_string.length()];
index = my_string.split("");
int cnt = 0;
int la = index.length;
for(int i=0; i<la; i++){
cnt = i+1;
while(cnt < la){
if(index[i].equals(index[cnt])){
index[cnt] = "";
}
cnt++;
}
}
answer = String.join("", index);
return answer;
}
}
반응형