【华为】2019校招(字符串解压缩,26进制和10进制相互转换)

字符串解压缩,a11b2bac3bad3abcd2,按照数量由少到多的顺序,数量相等的按照字典序,输出

ccccbbbbbdddddaaaaaaaaaaaaaa

竟然自己做了两个小时,加快编程速度,一定加快速度,注重准确性,正式笔试没有时间调试。

开始用i,j指针遍历找到字符和它的出现次数,用hashmap去重复,排序时用sort方法的重写Comparator接口

编写的比较麻烦,list-map-list的倒来倒去,磨磨唧唧

public static void reOrder() {
		String temp = "a11b2bac3bad3abcd2";
		// String temp="cd2";
		List<character> list = new ArrayList<>();
		int i = 0, j = 0;
		while (i < temp.length()) {
			if (temp.charAt(i) >= 'a' && temp.charAt(i) <= 'z') {
				character c = new character();
				c.chara = temp.charAt(i);
				j++;
				// 下一位还是字符不是数字,证明只有一个
				if (j < temp.length() && temp.charAt(j) >= 'a' && temp.charAt(j) <= 'z') {
					c.count = 1;
					list.add(c);
					i = j;
				} else {
					// 下一位是数字,但是不知道几位数字
					i = j;// 标记数字开始
					while (j < temp.length() && !(temp.charAt(j) >= 'a' && temp.charAt(j) <= 'z')) {
						j++;
					}
					j = j - 1;// 多加了一次
					int ten = 1;
					for (int index = j; index >= i; index--) {
						c.count += (temp.charAt(index) - '0') * ten;
						ten = ten * 10;
					}
					list.add(c);
					i = j + 1;
					j = i;
				}
			} else {

			}
		}
		HashMap<Character, Integer> map = new HashMap<>();
		// 用hashmap去重复合并
		for (i = 0; i < list.size(); i++) {
			if (map.containsKey(list.get(i).chara)) {
				map.put(list.get(i).chara, map.get(list.get(i).chara) + list.get(i).count);
			} else {
				map.put(list.get(i).chara, list.get(i).count);
			}
		}
		//加到list中方便排序
		List<character> list1 = new ArrayList();
		for (Entry<Character, Integer> entry : map.entrySet()) {
			list1.add(new character(entry.getKey(), entry.getValue()));
		}
		Collections.sort(list1, new Comparator<character>() {

			@Override
			public int compare(character o1, character o2) {
				// TODO Auto-generated method stub
				if (o1.count > o2.count) {
					return 1;
				} else if (o1.count < o2.count) {
					return -1;
				} else {
					// 数目相等字典序
					if (o1.chara > o2.chara) {
						return 1;
					} else if (o1.chara < o2.chara) {
						return -1;
					}
				}
				return 0;
			}
		});

		//测试输出
//		for (i = 0; i < list1.size(); i++) {
//			System.out.println(list1.get(i).chara + " " + list1.get(i).count);
//		}
		// 合并输出
		StringBuffer string = new StringBuffer("");
		for (i = 0; i < list1.size(); i++) {
			for (j = 0; j < list1.get(i).count; j++) {
				string.append(list1.get(i).chara);
			}
		}
		System.out.println(string.toString());
	}

26进制和10进制相互转换

public static String ToNumberSystem26(int n) {
		String s = "";
		while (n > 0) {
			int m = n % 26;
			s = (char) (m + 97) + s;
			if (m == 0) {
				m = 26;
			}
			n = (n - m) / 26;
		}
		return s;
	}

	public static int FromNumberSystem26(String s) {
		if (s == null)
			return 0;
		int n = 0;
		char[] arr = s.toCharArray();
		for (int i = s.length() - 1, j = 1; i >= 0; i--, j = j * 26) {
			char c = arr[i];
			n += ((int) (c - 97)) * j;
		}
		return n;
	}

猜你喜欢

转载自blog.csdn.net/wenyimutouren/article/details/82455241