题解 | #字符串合并处理#
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main{ public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // 合并 String str1 = sc.next(); String str2 = sc.next(); String str = str1 + str2; // 排序 str = sort(str); // 转换 str = transform(str); System.out.println(str); } private static String transform(String str) { StringBuffer sb = new StringBuffer(str.length()); for (char c : str.toCharArray()) { int n = 0; if(c >= 48 && c <= 57){ n = c - '0'; } else if(c >= 65 && c <= 70){ n = c - 'A' + 10; } else if(c >= 97 && c <= 102){ n = c -'a' + 10; } else { sb.append(c); continue; } sb.append(trans(n)); } return sb.toString(); } public static String trans(int n){ String binaryString = Integer.toBinaryString(n); while(binaryString.length() < 4){ binaryString = "0" + binaryString; } binaryString = new StringBuffer(binaryString).reverse().toString(); n = Integer.parseInt(binaryString, 2); return Integer.toHexString(n).toUpperCase(); } public static String sort(String str){ ArrayList<Character> evenList = new ArrayList<>(); ArrayList<Character> oddList = new ArrayList<>(); for (int i = 0; i < str.length(); i++) { if(i % 2 == 0){ evenList.add(str.charAt(i)); } else { oddList.add(str.charAt(i)); } } Collections.sort(evenList); Collections.sort(oddList); StringBuffer sb = new StringBuffer(str.length()); int i = 0; for (; i < evenList.size() && i < oddList.size(); i++) { sb.append(evenList.get(i)); sb.append(oddList.get(i)); } if(i != evenList.size()){ sb.append(evenList.get(evenList.size() - 1)); } return sb.toString(); } }