题解 | #字符串合并处理#
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String line = ""; if((line = bf.readLine()) != null){ String[] strs = line.split(" "); StringBuilder sb = new StringBuilder(); for(String str : strs){ sb.append(str); } int size = sb.toString().length(); char[] evens = new char[size % 2 == 1 ? size / 2 + 1 : size / 2]; char[] odds = new char[size / 2]; for(int i = 0;i < size;i++){ if(i % 2 != 1){ evens[i / 2] = sb.toString().substring(i,i+1).toCharArray()[0]; }else{ odds[i / 2] = sb.toString().substring(i,i+1).toCharArray()[0]; } } Arrays.sort(evens); Arrays.sort(odds); StringBuilder sbSorted = new StringBuilder(); for(int i = 0;i < size;i++){ if(i % 2 != 1){ sbSorted.append(evens[i / 2]); }else{ sbSorted.append(odds[i / 2]); } } HashMap<Character,Character> map = new HashMap<>(); char[] chs = sbSorted.toString().toCharArray(); ArrayList<Character> result = new ArrayList(); for(char c : chs){ result.add(c); } map.put('1','8'); map.put('2','4'); map.put('3','C'); map.put('4','2'); map.put('5','A'); map.put('7','E'); map.put('8','1'); map.put('A','5'); map.put('B','D'); map.put('C','3'); map.put('D','B'); map.put('E','7'); map.put('a','5'); map.put('b','D'); map.put('c','3'); map.put('d','B'); map.put('e','7'); map.put('f','F'); for(int i = 0;i < result.size();i++){ if(map.get(result.get(i)) != null){ result.set(i,map.get(result.get(i))); } } StringBuilder resSb = new StringBuilder(); for(Character c : result){ resSb.append(c); } System.out.println(resSb); } } }
- 判断一个数是否奇偶数,可以用以下方式
int num = 1; if(num % 2 == 0){ //为偶数 }else{ //为奇数 }
- 如果是奇偶数,可以通过String对象的toCharArray转化成为char数组遍历解决
String s = "sdsdadd"; char[] chs = s.toCharArray(); char[] evens = new char[chs.length / 2 + 1];//偶数位元素 char[] odds = new char[chs.length - evens.length];//奇数位元素 int j = 0,k = 0; for(int i = 0;i < chs.length;i++){ if(i % 2 == 0){//认为下标从0开始,第一个下标就为偶数位元素 //为偶数位元素 evens[j++] = chs[i]; }else{ //为奇数位元素 odds[k++] = chs[i]; } }