题解 | #字符串合并处理#
字符串合并处理
http://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
//这题的测试用例有坑
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str1 = sc.next();
String str2 = sc.next();
StringBuilder sb = new StringBuilder(str1 + str2);
List<Character> listJ = new ArrayList<>();
List<Character> listO = new ArrayList<>();
for (int i = 0; i < sb.length(); i++) {
if (i % 2 == 0) {
listO.add(sb.charAt(i));
} else {
listJ.add(sb.charAt(i));
}
}
Collections.sort(listJ);
Collections.sort(listO);
StringBuilder sb1 = new StringBuilder();
for (int i = 0, j = 0; i < sb.length(); i++) {
if (i % 2 == 0) {
sb1.append(listO.get(j));
} else {
sb1.append(listJ.get(j));
}
if (i % 2 != 0) {
j++;
} else {
continue;
}
}
String string = getRes(sb1.toString());
System.out.println(string);
}
}
private static String getRes(String s) {
char[] chars = s.toCharArray();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
if (Character.isDigit(chars[i])) {
StringBuilder sb = new StringBuilder(Integer.toBinaryString(chars[i] - '0'));
sb.reverse();
while (sb.length() < 4) {
sb.append("0");
}
int i1 = Integer.parseInt(sb.toString(), 2);
String string = Integer.toHexString(i1);
stringBuilder.append(string.toUpperCase());
} else if (Character.isLetter(chars[i]) && Character.toUpperCase(chars[i]) >= 'A' && Character.toUpperCase(chars[i]) <= 'F') {
StringBuilder sb = new StringBuilder(Integer.toBinaryString(Integer.parseInt(String.valueOf(chars[i]), 16)));
sb.reverse();
if (sb.length() < 4) {
sb.append("0");
}
int i1 = Integer.parseInt(sb.toString(), 2);
String string = Integer.toHexString(i1);
stringBuilder.append(string.toUpperCase());
}else {
stringBuilder.append(chars[i]);
}
}
return stringBuilder.toString();
}
}