题解 | #字符串合并处理#
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
Java实现:
思路清晰,代码简洁,欢迎大家交流讨论
代码如下,(注释的第一步、第二步、第三步 对应 题目描述 的处理):
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s1 = in.next();
String s2 = in.next();
// 1.第一步
char[] chars = s1.concat(s2).toCharArray();
// 2.第二步
// 偶数字符数组
char[] evens;
// 奇数字符数组
char[] odds;
if (chars.length % 2 == 0) {
evens = new char[chars.length / 2];
odds = new char[chars.length / 2];
} else {
evens = new char[(chars.length / 2) + 1];
odds = new char[chars.length / 2];
}
// 遍历原字符串数组,将奇偶下标的字符存至对应数组
boolean isEven = true; // 表示原字符串数组的当前下标是否为偶数位
for (int i = 0; i < chars.length; i++) {
if (isEven)
evens[i / 2] = chars[i];
else
odds[i / 2] = chars[i];
isEven = !isEven; // 转换奇偶性
}
// 排序
Arrays.sort(evens);
Arrays.sort(odds);
// 将奇偶数组放回原字符串数组
isEven = true;
for (int i = 0; i < chars.length; i++) {
if (isEven)
chars[i] = evens[i / 2];
else
chars[i] = odds[i / 2];
isEven = !isEven;
}
// 3.第三步
for (int i = 0; i < chars.length; i++) {
char ch = chars[i];
if ((ch >= '0' && ch <= '9')
|| (ch >= 'A' && ch <= 'F')
|| (ch >= 'a' && ch <= 'f')) {
// 解析为十六进制整数再转为二进制字符串
String binary = Integer.toBinaryString(Integer.parseInt(""+ch, 16));
// 二进制不足4位,则需前补零,补足4位
if (binary.length() < 4) {
int zeroFill = 4 - binary.length();
for (int j = 0; j < zeroFill; j++) {
binary = "0" + binary;
}
}
// 反转二进制
String reverse = new StringBuilder(binary).reverse().toString();
// 解析为2进制整数,再转为16进制字符串,再转成大写字母
char res = Integer.toHexString(Integer.parseInt(reverse, 2)).toUpperCase().charAt(0);
chars[i] = res;
}
}
// 输出结果
String ans = new String(chars);
System.out.println(ans);
}
}


