문제
내가 작성한 정답
class Solution {
public String solution(String cipher, int code) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < cipher.length(); i++){
if((i+1)%code==0){
sb.append(cipher.charAt(i));
}
}
return sb.toString();
}
}
다른 사람들의 정답
class Solution {
public String solution(String cipher, int code) {
String answer = "";
// code의 배수를 i로 설정하기 위해 code에 code를 더하는 식인 i += code를 사용한다.
for (int i = code; i <= cipher.length(); i = i + code) {
// code의 배수에 해당하는 인덱스의 문자를 추출하기 위해 i-1번째 문자열을 추출한다.
answer += cipher.substring(i - 1, i);
}
return answer;
}
}
substring(int beginIndex): 주어진 인덱스부터 문자열의 끝까지의 부분 문자열을 반환한다.
substring(int beginIndex, int endIndex): 주어진 시작 인덱스부터 종료 인덱스 전까지의 부분 문자열을 반환한다. 종료 인덱스는 포함되지 않는다.
StreamAPI
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class Solution {
public String solution(String cipher, int code) {
return IntStream.range(0, cipher.length())
// code로 나눈 값의 나머지가 code-1
// : index는 0부터 시작하므로 code의 배수번째를 구하려면 인덱스보다 +1 되어야한다.
.filter(value -> value % code == code - 1)
// 필터로 걸러낸 int값들에 해당하는 index에 존재하는 문자를 객체로 변환
.mapToObj(c -> String.valueOf(cipher.charAt(c)))
// 문자들을 연결하여 하나의 문자열로 반환
.collect(Collectors.joining());
}
}
Collectors.joining() 메서드는 기본적으로 스트림의 모든 요소를 연결하여 하나의 문자열로 반환한다.
- collect(Collectors.joining()): 스트림의 모든 요소를 빈 문자열로 연결
- collect(Collectors.joining(", ")): 요소들을 쉼표와 공백으로 구분하여 연결
- collect(Collectors.joining(", ", "[", "]")): 요소들을 쉼표와 공백으로 구분하고, 전체 문자열을 대괄호로 감싼다.
Share article