728x90
문제 설명
군 전략가 머쓱이는 전쟁 중 적군이 다음과 같은 암호 체계를 사용한다는 것을 알아냈습니다.
- 암호화된 문자열 cipher를 주고받습니다.
- 그 문자열에서 code의 배수 번째 글자만 진짜 암호입니다.
문자열 cipher와 정수 code가 매개변수로 주어질 때 해독된 암호 문자열을 return하도록 solution 함수를 완성해주세요.
제한사항
- 1 ≤ cipher의 길이 ≤ 1,000
- 1 ≤ code ≤ cipher의 길이
- cipher는 소문자와 공백으로만 구성되어 있습니다.
- 공백도 하나의 문자로 취급합니다.
입출력 예
cipher | code | result |
"dfjardstddetckdaccccdegk" | 4 | "attack" |
"pfqallllabwaoclk" | 2 | "fallback" |
입출력 예 설명
입출력 예 #1
- "dfjardstddetckdaccccdegk" 의 4번째, 8번째, 12번째, 16번째, 20번째, 24번째 글자를 합친 "attack"을 return합니다.
입출력 예 #2
- "pfqallllabwaoclk" 의 2번째, 4번째, 6번째, 8번째, 10번째, 12번째, 14번째, 16번째 글자를 합친 "fallback"을 return합니다.
[ 풀이 1 ]
1
2
3
4
5
6
7
|
class Solution {
public String solution(String cipher, int code) {
String answer = "";
for(int i=code-1;i<cipher.length();i+=code) answer += cipher.charAt(i);
return answer;
}
}
|
문자열.charAt(index) : index번째 글자를 가져옵니다. code 번째 부터 code만큼씩 건너띄면수 가져오면 됩니다. index가 0부터이므로 반복문의 시작은 code-1부터 시작해서 code만큼씩 건너띄기 하면 됩니다. 그래서 반복문은 for(int i=code-1;i<cipher.length();i+=code) 이렇게 됩니다. 이때 지정위치의 문자들만 뽑아서 결합하면 됩니다. |
[ 풀이 2 ]
1
2
3
4
5
6
7
8
9
10
|
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())
.filter(index -> (index+1) % code == 0)
.mapToObj(c -> String.valueOf(cipher.charAt(c)))
.collect(Collectors.joining());
}
}
|
0부터 문자열 길이만큼의 IntStream을 만들고 IntStream.range(0, cipher.length()) index값이 code, code*2, code*3...인 값으로 걸러서(주의 index는 0부터이나 숫자는 부터 이므로 +1을 함) .filter(index -> (index+1) % code == 0) 원하는 위치의 글자를 뽑아 String으로 만든다. .mapToObj(c -> String.valueOf(cipher.charAt(c))) 한개의 String객체로 변환한다. .collect(Collectors.joining()); |
728x90
'프로그래머스 코딩(자바) > Level 0' 카테고리의 다른 글
Programmers Level 0 - 문자열 정렬하기 (1) (0) | 2023.03.02 |
---|---|
Programmers Level 0 - 세균 증식 (0) | 2023.03.02 |
Programmers Level 0 - 대문자와 소문자 (0) | 2023.03.02 |
Programmers Level 0 - 가위 바위 보 (0) | 2023.03.02 |
Programmers Level 0 - 제곱수 판별하기 (0) | 2023.02.28 |