【华为机试037】字符串合并处理

题目描述:

将输入的两个字符串合并。

对合并后的字符串进行排序,要求为:下标为奇数的字符和下标为偶数的字符分别从小到大排序。这里的下标意思是字符在字符串中的位置。

对排序后的字符串进行操作,如果字符为‘0’——‘9’或者‘A’——‘F’或者‘a’——‘f’,则对他们所代表的16进制的数进行BIT倒序的操作,并转换为相应的大写字符。如字符为‘4’,为0100b,则翻转后为0010b,也就是2。转换后的字符为‘2’; 如字符为‘7’,为0111b,则翻转后为1110b,也就是e。转换后的字符为大写‘E’。


举例:输入str1为"dec",str2为"fab",合并为“decfab”,分别对“dca”和“efb”进行排序,排序后为“abcedf”,转换后为“5D37BF”

Java实现:

import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;

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();
            String str = str1 + str2;
            char[] chars = str.toCharArray();
            int len1, len2;
            if (chars.length % 2 == 0 ) {
                len1 = chars.length/2;
                len2 = len1;

            }else {
                len1 = chars.length/2 + 1;
                len2 = chars.length/2;
            }
            char[] chars1 = new char[len1];
            char[] chars2 = new char[len2];

            for (int i = 0, m = 0, n = 0; i < chars.length; i++) {
                if (i % 2 == 0)
                    chars1[m++] = chars[i];
                else
                    chars2[n++] = chars[i];
            }

            Arrays.sort(chars1);
            Arrays.sort(chars2);

            for (int i = 0, m = 0, n = 0; i < chars.length; i++) {
                if (i % 2 == 0)
                    chars[i] = chars1[m++];
                else
                    chars[i] = chars2[n++];
            }

            HashMap<Character, Character> 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');

            for (int i = 0; i < chars.length; i++) {
                if (map.containsKey(chars[i]))
                    chars[i] = map.get(chars[i]);
            }


            //System.out.println(Arrays.toString(chars));
            System.out.println(String.valueOf(chars));
        }
    }
}

知识点:

  • 注意读懂题意,只是将十六进制的字符转换为大写,而不是全部字母
  • HashMap中的containsKey方法判断是否包含某个键

猜你喜欢

转载自blog.csdn.net/heyiamcoming/article/details/80893601