题解 | #字符串合并处理#
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { //将输入字符串合拼一个整字符串 String s = sc.nextLine().replace(" ", ""); System.out.println(order(s)); } } private static String order(String s) { //将按照下表将字符分割成奇数偶数数组 List<Character> evenList = new ArrayList<>(); List<Character> oddList = new ArrayList<>(); for (int i = 0; i < s.length(); i++) { if (i % 2 == 0 ) { evenList.add(s.charAt(i)); } else { oddList.add(s.charAt(i)); } } //奇数偶数进行排序 evenList.sort(Comparator.comparingInt(o -> o)); oddList.sort((o1, o2) -> o1 - o2); //将偶数数组和奇数数组按排序后的奇偶数组合并 int lens = evenList.size() + oddList.size(); // char[] chars = new char[lens]; StringBuilder merge = new StringBuilder(); for (int i = 0, j = 0, z = 0; i < lens; i++) { if (i % 2 == 0) { merge.append(convert(evenList.get(j++))); } else { merge.append(convert(oddList.get(z++))); } } return merge.toString(); } //暴力方法解决convert() private static char convert(char ch) { // 数字0、6 和9 转换二进制 在进行并排序 还是本身 switch (ch) { case '1': return '8'; case '2': return '4'; case '3': return 'C'; case '4': return '2'; case '5': return 'A'; case '7': return 'E'; case '8': return '1'; case 'A': return '5'; case 'a': return '5'; case 'B': return 'D'; case 'b': return 'D'; case 'c': return '3'; case 'C': return '3'; case 'D': return 'B'; case 'd': return 'B'; case 'e': return '7'; case 'E': return '7'; case 'f': return 'F'; default: return ch; } } }