题目描述:
给出一个01字符串(长度不超过100),求其每一个子串出现的次数。
输入:
输入包含多行,每行一个字符串。
输出:
对每个字符串,输出它所有出现次数在1次以上的子串和这个子串出现的次数,输出按字典序排序。
样例输入:
10101
样例输出:
0 2
01 2
1 3
10 2
101 2
#include "stdio.h"
#include "math.h"
#include "stdlib.h"
#include "string.h"
typedef struct{
char ch[101];
int value2;
struct Node *left;
struct Node *right;
}Node,*BiTree;
void insert(BiTree *b,char *ch2);
void find (BiTree b,char *ch,BiTree *b2);
void print (BiTree b);
char * copy (char *des,char *src,int start,int end);
void destroy (BiTree *b);
int main () {
char ch[101];
char ch2[101];
BiTree b = NULL;
int i,j,length;
while (scanf ("%s",ch)!=EOF) {
length = strlen (ch);
for (i = 1;i <=length;i++){
for (j = 0;j < length;j++) {
if (j + i <= length) {
copy (ch2,ch,j,j+i);
insert (&b,ch2);
}
}
}
print(b);
destroy(&b);
}
return 0;
}
void insert (BiTree *b,char *ch2) {
if (*b == NULL) {
(*b) = (BiTree)malloc(sizeof(Node));
strcpy((*b)->ch,ch2);
(*b)->value2 = 1;
(*b)->left = (*b)->right = NULL;
}else {
BiTree b2,b3;
find (*b,ch2,&b2);
if (b2 !=NULL) {
b3= (BiTree)malloc(sizeof (Node));
b3->left = b3->right = NULL;
b3->value2 = 1;
strcpy((b3)->ch,ch2);
if (strcmp (b2->ch,ch2) > 0) {
b2->left = b3;
}else {
b2->right = b3;
}
}
}
}
void find (BiTree b,char *ch,BiTree *b2) {
if (b == NULL) {
return;
}else {
if (strcmp(b->ch,ch) == 0) {
b->value2++;
*b2 = NULL;
return;
}else if (strcmp (b->ch,ch) > 0 ) {
*b2 = b;
find (b->left,ch,b2);
}else {
*b2 = b;
find (b->right,ch,b2);
}
}
}
void print (BiTree b) {
if (b == NULL) {
return;
}else {
print(b->left);
if (b->value2 >1) {
printf("%s %d\n",b->ch,b->value2);
}
print(b->right);
}
}
char * copy (char *des,char *src,int start,int end) {//不包括end的值
int index = 0;
for (;start < end;start++) {
des[index++] = src[start];
}
des[index] = '\0';
}
void destroy (BiTree *b) {
free(*b);
*b= NULL;
}