CodeWars 编解码问题

*Description:

For building the encrypted string:
Take every 2nd char from the string, then the other chars, that are not every 2nd char, and concat them as new String.
Do this n times!
Examples:
“This is a test!”, 1 -> “hsi etTi sats!”
“This is a test!”, 2 -> “hsi etTi sats!” -> “s eT ashi tist!”

String encrypt(final String text, final int n)
String decrypt(final String encryptedText, final int n)

For both methods:
If the input-string is null or empty return exactly this value!
If n is <= 0 then return the input text.

  1. 作者的方法中首先用了StringBuilder 可变的字符串变量
  2. 用到了递归的方法,节约时间
public class Kata {

  public static String encrypt(final String text, int n) {
                if (n <= 0 || text == null || text.isEmpty()) {
                        return text;
                }

                StringBuilder firstPart = new StringBuilder();
                StringBuilder secondPart = new StringBuilder();
                for (int i = 0; i < text.length(); i++) {
                        char aChar = text.charAt(i);
                        if (i % 2 == 1) {
                                firstPart.append(aChar);
                        } else {
                                secondPart.append(aChar);
                        }
                }

                return encrypt(firstPart.append(secondPart).toString(), --n);
        }

        public static String decrypt(final String encryptedText, int n) {
                if (n <= 0 || encryptedText == null || encryptedText.isEmpty()) {
                        return encryptedText;
                }

                StringBuilder text = new StringBuilder();
                final int half = encryptedText.length() / 2;
                for (int i = 0; i < half; i++) {
                        text.append(encryptedText.charAt(half + i)).append(encryptedText.charAt(i));
                }
                if (encryptedText.length() % 2 == 1) {
                        text.append(encryptedText.charAt(encryptedText.length() - 1));
                }

                return decrypt(text.toString(), --n);
        }

}

你可能感兴趣的:(CodeWars)