Study with me/프로그래머스 L0 마스터하기
프로그래머스 - L0 글자지우기
외계나무
2024. 1. 18. 23:09
별 생각 없이 풀었다. 사실 for문은 하나만 쓰고 싶어서 이렇게 풀었다.
import java.util.Arrays;
class Solution {
public String solution(String my_string, int[] indices) {
String answer = "";
String[] plus = my_string.split("");
Arrays.sort(indices);
int j = 0;
for(int i=0; i<plus.length; i++){
if(indices[j]==i) {
j++;
} else {
answer += plus[i];
}
if(j>=indices.length)
j = 0;
}
return answer;
}
}
for 문을 한 번만 쓰는 것에는 이런 방법도 있었다... 내가 두 번째 if로 뺀 조건을 &&으로 처리해버리기 ㅎ
import java.util.*;
class Solution {
public String solution(String my_string, int[] indices) {
String answer = "";
int j=0;
Arrays.sort(indices);
for(int i=0;i<my_string.length();i++){
if(j<indices.length && i==indices[j] ){
j++;
}else{
answer += my_string.charAt(i);
}
}
return answer;
}
}
이건 for문을 두 개 쓰긴 했지만 String 배열에서 미리 해당하는 원소를 제거하는 방식. 가장 많은 사람들이 쓴 모양.
class Solution {
public String solution(String my_string, int[] indices) {
String answer = "";
String[] tmp = my_string.split("");
for (int i = 0; i < indices.length; i++) {
tmp[indices[i]] = "";
}
for (String x : tmp) {
answer += x;
}
return answer;
}
}
그리고 전설의 스트림... ㅋㅋㅋㅋㅋㅋ 멋있긴 한데, 나중에라도 이렇게 할 것 같지는 않다 ㅋㅋㅋ
import java.util.stream.*;
class Solution {
public String solution(String myString, int[] indices) {
return IntStream.range(0, myString.length())
.filter(i -> !IntStream.of(indices)
.boxed()
.collect(Collectors.toSet())
.contains(i))
.mapToObj(myString::charAt)
.map(Object::toString)
.collect(Collectors.joining());
}
}