题目:
- 数字(0~9)使用对应的大写字母代替(”ZERO”, “ONE”, “TWO”, “THREE”, “FOUR”, “FIVE”, “SIX”, “SEVEN”, “EIGHT”, “NINE”),并随机打乱这些字母。现需要对其整理。
思路:
- 0是独占Z,2独占W,4独占U,6独占X,8独占G,这些可以先计算,然后去除上面的。接着有7独占S,5独占F,3独占H,1和9通过O和I来区分。因此只需按照(0,2,4,6,8,3,5,7,1,9)这个顺序,即可统计出这个字符串中包含的各个数字分别有多少个。
代码:
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNextLine()){
String str = in.nextLine();
int n = Integer.parseInt(str);
for(int i=0; i<n; i++){
String inputStr = in.nextLine();
String result = MyFunction(inputStr);
System.out.println(result);
}
}
}
public static String MyFunction(String str){
char[] charOrder = {'Z','W','U','X','G','H','F','S','O','I'};
int[] numOrder = {0, 2, 4, 6, 8, 3, 5, 7, 1, 9};
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(0, "ZERO");
map.put(1, "ONE");
map.put(2, "TWO");
map.put(3, "THREE");
map.put(4, "FOUR");
map.put(5, "FIVE");
map.put(6, "SIX");
map.put(7, "SEVEN");
map.put(8, "EIGHT");
map.put(9, "NINE");
//统计字符串中各字符的数目,对应到0~25.
int[] cntForChar = new int[26];
for(int i=0; i<str.length(); i++){
int temp = str.charAt(i)-'A';
cntForChar[temp]++;
}
// 统计0~9各个数字的个数
int[] cntForNums = new int[10];
for (int i = 0; i <= 9; i++) {
// 按照 charOrder、numOrder的顺序逐个遍历(即在cntForChar中将它们删去)
int temp_num = numOrder[i];
char temp_ch = charOrder[i];
// 根据特定的字符判断特定的数字有多少个。
cntForNums[temp_num] = cntForChar[temp_ch - 'A'];
// 删除该数字所占的所有字符
String temp_str = map.get(temp_num);
for (int j = 0; j < temp_str.length(); j++) {
int index = temp_str.charAt(j) - 'A';
cntForChar[index] -= cntForNums[temp_num];
}
}
//------ 题目:先加8再取个位 。 所以这一步就是逆操作 -----------
int[] beforeAdd = new int[10];
for(int i=0; i<=9; i++){
int index = (i-8>=0)?(i-8):(i+10-8);
beforeAdd[index] = cntForNums[i];
}
//输出,这步要注意 res 应该加在右边还是右边
String res = "";
for(int i=9;i>=0;i--){
for(int j=0; j<beforeAdd[i];j++)
res = i + res;
}
return res;
}
}
参考:
题目:http://exercise.acmcoder.com/online/online_judge_ques?ques_id=3327&konwledgeId=155
思路:http://www.cnblogs.com/Keven02/p/6435659.html