Contents

Decryption (with.Java)

   Feb 22, 2024     2 min read

This is an article about the “decryption” problem.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.

Let’s look at the problem first.

problem

Military strategist Murseogi discovered that the enemy used the following encryption system during the war.

Send and receive encrypted string ciphers.

In that string, only the letters that are multiples of code are the real password.

Complete the solution function to return the decrypted cipher string when the string cipher and integer code are given as parameters.

Restrictions

  • 1 ≤ cipher length ≤ 1,000
  • 1 ≤ code ≤ length of cipher
  • The cipher consists only of lowercase letters and spaces.
  • Spaces are also treated as one character.

Input/Output Example

ciphercoderesult
“dfjardstddetckdaccccdegk”4“attack”
“pfqallllabwaoclk”2“fallback”

My solution to the problem

class Solution {
     public String solution(String cipher, int code) {
         StringBuilder sb = new StringBuilder();
         int max = cipher.length() / code;
         for(int i = 1; i <= max; i++){
             int temp = i * code;
             sb.append(cipher.charAt(temp - 1));
         }
         return sb.toString();
     }
}

Solution explanation

First, we create sb, a StringBuilder object. This object is used to process strings efficiently.

Next, the length of the cipher divided by the code is stored in max. This indicates the number of characters to extract.

And then iterate through the numbers from 1 to max through a for loop. This indicates the location of the character to extract.

Inside the loop, the value multiplied by i and code is stored in the temp variable. This is used to calculate the index of the character to be extracted.

And add cipher.charAt(temp - 1) to sb. The charAt method returns the character corresponding to the given index. Subtract 1 because the index of temp - 1 starts from 0, while temp starts from 1.

Finally, we call sb.toString() to convert the StringBuilder object to a string and return it.

This returns a new string containing the characters extracted at code intervals from the cipher string in order.