字符串合并处理
字符串合并处理
http://www.nowcoder.com/questionTerminal/d3d8e23870584782b3dd48f26cb39c8f
import java.util.*; public class Main { private Map<Character, Character> map; public Main() { map = new HashMap<>(); map.put('0', '0'); map.put('1', '8'); map.put('2', '4'); map.put('3', 'C'); map.put('4', '2'); map.put('5', 'A'); map.put('6', '6'); map.put('7', 'E'); map.put('8', '1'); map.put('9', '9'); map.put('a', '5'); map.put('b', 'D'); map.put('c', '3'); map.put('d', 'B'); map.put('e', '7'); map.put('f', 'F'); map.put('A', '5'); map.put('B', 'D'); map.put('C', '3'); map.put('D', 'B'); map.put('E', '7'); map.put('F', 'F'); } private String sort(String merge) { char[] even = new char[(merge.length() + 1) / 2]; char[] odd = new char[merge.length() / 2]; for (int i = 0, j = 0; i < even.length; j += 2) { even[i++] = merge.charAt(j); } for (int i = 0, j = 1; i < odd.length; j += 2) { odd[i++] = merge.charAt(j); } Arrays.sort(even); Arrays.sort(odd); StringBuilder s = new StringBuilder(); for (int i = 0; i < even.length || i < odd.length; i++) { if (i < even.length) { s.append(even[i]); } if (i < odd.length) { s.append(odd[i]); } } return s.toString(); } // 找了好久,这里有坑,若字符不在map中,则保留原值 private String transfer(String str) { StringBuilder s = new StringBuilder(); for (char ch : str.toCharArray()) { s.append(map.getOrDefault(ch, ch)); } return s.toString(); } public String processString(String str1, String str2) { String merge = sort(str1 + str2); String res = transfer(merge); return res; } public static void main(String[] args) { Main solution = new Main(); Scanner in = new Scanner(System.in); while (in.hasNext()) { String str1 = in.next(); String str2 = in.next(); String res = solution.processString(str1, str2); System.out.println(res); } } }