问题:输入多个(m)给定长度(n)的字符串。
输出:将字符串按照字符逆序数,从小到大进行输出,如果两个字符串的逆序数一样,则按照字母表的顺序输出。
解决:
1.求的字符串的逆序数
求逆序数这里不过多阐述,明白什么是逆序数,编码很简单。
2.将字符串排列好。
如何将字符串排列好,然后有序输出。这里保存字符串的数据结构设计直接决定的编码的复杂程度。这里我选用的是hash。解决冲突的办法就是链式法。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct CHAR
{
char c[ 51 ] ;
struct CHAR* next ;
} HASH;
HASH hash[ 1276 ] ;
int main()
{
int n, m ;
HASH *temp ;
int hashValue ;
HASH *p1 ;
HASH *p2 ;
// FILE *fp = fopen( "in.txt", "r" ) ;
//init hash
for (int i = 0; i < 1276; ++i)
{
hash[ i ].c[0] = '0' ;
hash[ i ].next = NULL ;
}
// fscanf( fp, "%d %d", &n, &m ) ;
scanf( "%d %d", &n, &m ) ;
// printf("n = %d\tm = %d\n", n, m );
while( m-- )
{
temp = (HASH*)malloc( sizeof(HASH) * 1) ;
// fscanf( fp, "%s", temp->c ) ;
scanf( "%s", temp->c ) ;
temp->next = NULL ;
// printf("%s\t", temp->c);
//sum hash value
hashValue = 0 ;
for (int i = 0; i < n; ++i)
{
for (int j = i + 1; j < n; ++j)
{
if ( temp->c[ i ] > temp->c[ j ] )
{
hashValue++ ;
}
}
}
// printf("hashValue = %d\n", hashValue);
//insert
p1 = hash[ hashValue ].next ;
p2 = &hash[ hashValue ] ;
while( p1 != NULL && strcmp( p1->c, temp->c) < 0 )
{
p2 = p1 ;
p1 = p1->next ;
}
temp->next = p2->next ;
p2->next = temp ;
// printf("%s\n", hash[hashValue].next->c);
}
for (int i = 0; i <= 1276; ++i)
{
p1 = hash[ i ].next ;
while( p1 != NULL )
{
printf("%s\n", p1->c);
p1 = p1->next ;
}
}
return 0 ;
}