암호해독

Wook·2024년 9월 27일

🧩코딩테스트

목록 보기
41/46
post-thumbnail

문제

군 전략가 머쓱이는 전쟁 중 적군이 다음과 같은 암호 체계를 사용한다는 것을 알아냈습니다.

  • 암호화된 문자열 cipher를 주고받습니다.
  • 그 문자열에서 code의 배수 번째 글자만 진짜 암호입니다.

문자열 cipher와 정수 code가 매개변수로 주어질 때 해독된 암호 문자열을 return하도록 solution 함수를 완성해주세요.

조건

  • 1 ≤ cipher의 길이 ≤ 1,000
  • 1 ≤ code ≤ cipher의 길이
  • cipher는 소문자와 공백으로만 구성되어 있습니다.
  • 공백도 하나의 문자로 취급합니다.

예시

ciphercoderesult
"dfjardstddetckdaccccdegk"4"attack"
"pfqallllabwaoclk"2"fallback"

풀이

  • 반복문을 사용해 문자열 연산이 계속 이루어지므로 StringBuilder로 변수를 선언한다
  • String.charAt()를 사용할 것이기 때문에 초기식은 code - 1 로 설정하고 증감식은 code의 정수값만큼 증가시킨다
  • StrigBuilder.append() 메서드를 사용하여 해당되는 문자를 더하고, 마지막엔 String으로 반환한다

코드

class Solution {
    public String solution(String cipher, int code) {
        StringBuilder answer = new StringBuilder();
        for(int i = code - 1; i < cipher.length(); i += code){
            answer.append(cipher.charAt(i));
        }
        
        return answer.toString();
    }
}
profile
Keep going

0개의 댓글