注释详解 | #字符串合并处理#
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String str = in.nextLine();
str = str.replace(" ", "");
char[] chars = str.toCharArray();
int count = chars.length / 2;
// 考虑总数量不是偶数的情况
int count2 = chars.length % 2;
String[] string1 = new String[count + count2];
String[] string2 = new String[count];
// TreeSet<String> string1 = new TreeSet<>();
// TreeSet<String> string2 = new TreeSet<>();
// 分类排序
for (int i1 = 0, i2 = 0, i = 0; i < chars.length; i++) {
String s = String.valueOf(chars[i]);
if (i % 2 == 0) {
// 奇数位
string1[i1] = s;
i1++;
} else {
// 偶数位
string2[i2] = s;
i2++;
}
}
Arrays.sort(string1);
Arrays.sort(string2);
// 重组
for (int i1 = 0, i2 = 0, i = 0; i < chars.length; i++) {
String s = "";
if (i % 2 == 0) {
// 奇数位
s = string1[i1];
i1++;
} else {
s = string2[i2];
i2++;
}
// 不在需要操作的范围
if(s.replaceAll("[0-9]","").replaceAll("[a-f]","").replaceAll("[A-F]","").equals(s)){
System.out.print(s);
continue;
}
// 不属于0-9
if (s.replaceAll("[0-9]", "").equals(s)) {
// 将16进制转为10进制
s = String.valueOf(Integer.parseInt(s, 16));
}
// 10进制转为2进制
String to2 = Integer.toBinaryString(Integer.parseInt(s));
// 补0
if (to2.length() < 4) {
StringBuilder stringBuilder = new StringBuilder(to2);
for (int j = to2.length(); j < 4; j++) {
stringBuilder.insert(0, 0);
}
to2 = stringBuilder.toString();
}
// 反转
StringBuilder reverse = new StringBuilder(to2).reverse();
// 2进制转为10进制
int to10 = Integer.parseInt(reverse.toString(), 2);
// 不属于0-9
if (!(to10 >= 0 && to10 <= 9)) {
// 转为16进制
String result = Integer.toHexString(to10);
System.out.print(result.toUpperCase());
} else {
System.out.print(to10);
}
}
}
}
}
