Didi Autumn Recruitment 2021-0913 Question 1 Reverse String

Title: A
certain X star invented an encryption method, which is to split a plaintext string from left to right into several substrings of equal length (the length of the last substring can be different), and then divide each The characters in each substring are reversed to obtain the ciphertext.
Now that you have successfully intercepted the ciphertext of the X star and guessed the length set by the X star, can you write a program to crack the ciphertext to get the corresponding plaintext?

Input description: The input of a
single group of
test data occupies two lines. The first line contains a positive integer n, which represents the length of each substring; the second line is the encrypted string S (S length<=1000,n <=100) The
ciphertext may contain English uppercase and lowercase letters, numbers, spaces and English punctuation.

Output description:
The output of each group of test data occupies one line, which represents the plaintext obtained after cracking the ciphertext.

Sample input:
2
gogogoout

Sample output:
ogogoguot

Idea:
According to the conventional solution, split the string into equal-length substrings with a length of n, and then write a string reversal method, and then merge the substrings after reversing.

Code: AC 100%

package QiuZhao_2021_0913;

import java.util.Scanner;

public class Fir {
    
    

    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.nextLine());
        StringBuffer sb = new StringBuffer(sc.nextLine());
        String str = sb.toString();
        for (int i = 0; i < str_split(str, n).length; i++) {
    
    
            System.out.print(reserveStr(str_split(str, n)[i]));
        }
    }

    //写一个反转字符串的方法
    public static String reserveStr(String s) {
    
    
        return new StringBuffer(s).reverse().toString();
    }

    //写一个方法,分割字符串
    public static String[] str_split(String str, int length) {
    
    
        int len = str.length();
        String[] s = new String[(len + length - 1) / length];
        for (int i = 0; i < len; i += length) {
    
    
            int n = len - i;
            if (n > length)
                n = length;
            s[i / length] = str.substring(i, i + n);
        }
        return s;
    }
}

If there is a better solution, please comment and exchange!

Guess you like

Origin blog.csdn.net/weixin_43419256/article/details/108568253