题意:找出字符串x, x的某个排序是strA的子串, x的某个排序是strB的子串。
思路:方法多种。1. 统计。用两个26的数组分别保存A B串中出现的字母的频数, 输出时, 从a开始输出, 每次输出 min(letterA[i], letterB[i])个字母。
2.对两个字符串排序, 然后从头到尾输出一样的字母, 考虑个数。
3.找出有一样的字母(考虑个数), 然后对这些字母排序。
算法复杂度: 方法1. 统计两串的字母频数 o(2N) + 输出字母 o(26) ≈ o(2N).
代码:
#include <cstdio>
#include <cstring>
using namespace std;
#define MAX_N 1005
void count(char *, int *);
int main()
{
char a[MAX_N], b[MAX_N];
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
while (fgets(a, sizeof(a), stdin) && fgets(b, sizeof(b), stdin)) {
//init
int mapA[26], mapB[26];
memset(mapA, 0, sizeof(mapA));
memset(mapB, 0, sizeof(mapB));
//count
count(a, mapA);
count(b, mapB);
//output
for (int i = 0; i < 26; i++) {
int min = mapA[i] > mapB[i] ? mapB[i] : mapA[i];
for (int j = 0; j < min; j++) {
printf("%c", 'a' + i);
}
}
printf("\n");
}
return 0;
}
void count(char *str, int *map)
{
for (char *p = str; *p; p++) {
map[*p - 'a']++;
}
}