A - Santa Claus and Keyboard Check
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
InputThe input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
helloworld ehoolwlroz
3 h e l o d z
hastalavistababy hastalavistababy
0
merrychristmas christmasmerry
-1
题意:对比输入的两个字符串,如果不相同的字符一一对应,则输出需交换的字符对数以及交换的字符内容;若两字符串相同,则输出0;若不是一一对应关系则输出-1。
我的思路是,把字符串存入a, b两个数组中,如果字符串不同,循环对比,将不同的两个字符存入c, d两个数组,在这之前需要一个循环判断此次比较的字符书否已经存入,存过就不再存了,保证不同的字符是一一对应的,最后将数组中的不同字符替换再strcmp一边,相同就输出c, d数组中的字符,不同则为-1.
代码如下:
#include<stdio.h> #include<string.h> int main(){ char a[1005], b[1005], c[1005], d[1005]; while(scanf("%s", a) != EOF){ scanf("%s", b); if(!strcmp(a, b)){ printf("0\n"); continue; } int len = strlen(a), num = 0, flag; for(int i = 0; i < len; i++){ flag = 0; if(a[i] != b[i]){ for(int k = 0; k < num; k++){ if(a[i] == c[k] || a[i] == d[k] || b[i] == c[k] || b[i] == d[k]) flag = 1; } if(!flag){ c[num] = a[i]; d[num++] = b[i]; } } } for(int i = 0; i < len; i++){ for(int j = 0; j < num; j++){ if(a[i] == c[j]){ a[i] = d[j]; break; } else if(a[i] == d[j]){ a[i] = c[j]; break; } } } if(!strcmp(a, b)){ printf("%d\n", num); for(int i = 0; i < num; i++){ printf("%c %c\n", c[i], d[i]); } } else printf("-1\n"); } return 0; }