(小米笔试)打乱字符串还原

时间:2021-02-24 14:39:13
#include <stdio.h>
#include <string.h>
int need[10][26];
void init() {
char str[10][6] = { "ZERO","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE" };
int i, j;
for (i = 0; i < 10; i++) {
for (j = 0; j < strlen(str[i]); j++) {
need[i][str[i][j] - 'A']++;
}
}
}
int find_it[10] = { 8,9,0,1,2,3,4,5,6,7 }; //搜索顺序
int ans[4000];
int dfs(int ques[],int cur) {
int i;
int sum = 0;
for (i = 0; i < 26; i++)
sum += ques[i];
if (sum == 0)
return cur; //搜索成功,拥有的字符个数均为0了,返回ans的个数
int j;
int lp = 0;
for (i = 0; i < 10; i++) {
bool flag = true;
for (j = 0; j < 26; j++) {
if (need[find_it[i]][j] > ques[j]) {
flag = false;
break;
}
}
if (flag) {
for (j = 0; j < 26; j++) {//拥有的字符串都大于需要的
ques[j] -= need[find_it[i]][j]; //减去需要的,继续搜索
}
ans[cur] = i;
lp = 1;
int k = dfs(ques, cur + 1); //如果返回了0,则表示这次搜索失败,需要继续搜索,因为是从最优的解开始搜索
if (k != 0) //一旦成功就可以直接输出结果
return k;
}
}
return 0;
}
int main() {
int i, j;
for (i = 0; i < 10; i++)
for (j = 0; j < 26; j++)
need[i][j] = 0;
init();
char str[10001];
int ques[26];

int n;
scanf("%d", &n);
while (n--) {
for (i = 0; i < 4000; i++)
ans[i] = -1;
int num = 0;
scanf("%s", str);
for (i = 0; i < 26; i++) {
ques[i] = 0;
}
for (i = 0; i < strlen(str); i++) { //被打乱的字符串各个字母的个数
ques[str[i] - 'A']++;
}
num = dfs(ques, 0);
i = 0;
while(i<num) {
printf("%d",ans[i++]);
}
printf("\n");
}
}