有点绕的字符串操作,加密很简单,解密没思路,看了大神的题解就明白了,顺便附上
// 解密的话贪心处理:// 由排序方式可知,排头的字母肯定是字符串排序后得到的。// 因此对加密串排序,则排序后与排序前的两个串分别是加密最后一步得到的矩阵首列和尾列。// 称此二序列为 s1 和 s2。// 不难分析得到,s2[i] 在明文的后继就是 s1[i]。// 而且如果给出明文的第一个字符是 c,那么由于排序的稳定性,// 可以找出这第一个串字符所在的位置就是 pos = s1.find_first_of(c)。// 而它的前驱则是确定的,就是 s2[i],而且我知道这时候 s2[i] 是最后一个字符。// 那么,要找到 s2[i] 实际所在字符串的位置就应该是 pos' = s1.find_last_of(s2[pos]),// 因为这个字符是最后的,他在排序之后肯定也要处于同样开头的字符串中的最后。// 然后将 pos' 代入 pos,重复进行操作。// 另:每次从 s1 中查找到一个 pos 之后,必须执行 s1[pos] = ' ',把它擦掉。// 这样一来,第二次找上去的,就是 "倒数第二个",如此类推。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct String
{
char s[100];
int index;
};
static int cmp(const void *p1, const void *p2)
{
struct String *s1 = (struct String*) p1;
struct String *s2 = (struct String*) p2;
if (s1->s[0] != s2->s[0])
return s1->s[0] - s2->s[0];
else
return s1->index - s2->index;
}
static void encode(char *s)
{
int i, j, len = strlen(s);
struct String *array = malloc(len * sizeof(struct String));
for (i = 0; i < len; i++)
{
char *t = array[i].s;
array[i].index = i;
int total = 0;
for (j = i; j < len; j++)
t[total++] = s[j];
for (j = 0; j < i; j++)
t[total++] = s[j];
}
qsort(array, len, sizeof(struct String), cmp);
for (i = 0; i < len; i++)
putchar(array[i].s[len - 1]);
putchar('\n');
free(array);
}
static int cmp_char(const void *p1, const void *p2)
{
char *c1 = (char *) p1;
char *c2 = (char *) p2;
return *c1 - *c2;
}
static int first_index(char *s, int len, char c)
{
int i;
for (i = 0; i < len; i++)
if (s[i] == c)
return i;
return -1;
}
static int last_index(char *s, int len, char c)
{
int i;
for (i = len - 1; i >= 0; i--)
if (s[i] == c)
return i;
return -1;
}
static void decode(char *s)
{
int i, len = strlen(s) - 1;
char first[100], last[100], res[100];
strncpy(first, s, len);
strncpy(last, s, len);
qsort(first, len, sizeof(char), cmp_char);
char begin = s[len];
res[0] = begin;
int li, fi = first_index(first, len, begin);
first[fi] = 0;
char cc = last[fi];
int index = len - 1;
res[index--] = cc;
while ((li = last_index(first, len, cc)) != -1)
{
first[li] = 0;
cc = last[li];
res[index--] = cc;
}
for (i = 0; i < len; i++)
putchar(res[i]);
putchar('\n');
}
int main()
{
char flag[7], str[101];
while (scanf("%s %s", flag, str) != EOF)
if (strcmp("encode", flag) == 0)
encode(str);
else
decode(str);
return 0;
}