对字符串的每一个字符进行哈夫曼编码

前言

个人小记


一、代码如下

#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ARR 100
#define MAX_S 1000
typedef struct Node
{
    char ch;
    int f;
    struct Node* lchild,*rchild;
}Node;

Node* init_node(char ch,int f)
{
    Node* node=(Node*)malloc(sizeof(Node));
    node->ch=ch;
    node->f=f;
    node->lchild=node->rchild=NULL;
    return node;
}

void clear_tree(Node* root)
{
    if(root==NULL)return ;
    clear_tree(root->lchild);
    clear_tree(root->rchild);
    free(root);
    return ;
}

int FindMIN(Node** arr,int n)
{
    int min=arr[0]->f;
    int pos=0;
    for(int i=1;i<n;i++)
    {
        if(arr[i]->f<min)
        {
            min=arr[i]->f;
            pos=i;
        }
    }
    return pos;
}

void swap(Node** a,Node** b)
{
    Node* t=*a;
    *a=*b;
    *b=t;
    return ;
}


void putout_halfman(Node* root,char buff[],int k)
{
    buff[k]=0;
    if(root->lchild==NULL&&root->rchild==NULL)
    {
        printf("%c %s\n",root->ch,buff);
        return ;
    }
    buff[k]='0';
    putout_halfman(root->lchild,buff,k+1);
    buff[k]='1';
    putout_halfman(root->rchild,buff,k+1);
    return ;
}

Node* build_halfman_tree(Node** arr,int n)
{
    for(int i=0;i<n-1;i++)
    {
        int Min1=FindMIN(arr,n-i);
        swap(&arr[Min1],&arr[n-i-1]);
        int Min2=FindMIN(arr,n-i-1);
        swap(&arr[Min2],&arr[n-i-2]);
        int new=arr[n-i-1]->f+arr[n-i-2]->f;
        Node* node=init_node('0',new);
        node->lchild=arr[n-i-1];
        node->rchild=arr[n-i-2];
        arr[n-i-2]=node;
    }
    return arr[0];
}

void count(char s[],int str[])
{
    int len=strlen(s);
    for(int i=0;i<len;i++)
    {
        str[(unsigned char)s[i]]++;
    }
    return ;
}
int main()
{
    int str[256]={0},t=0;
    printf("请输入字符串:");
    char s[MAX_S];
    fgets(s,MAX_S,stdin);
    //s[strcspn(s,'\n')]=0;
    char *newline = strchr(s, '\n');
    if (newline != NULL) *newline = '\0';

    count(s,str);
    for(int i=0;i<256;i++)
    {
        if(str[i])t++;
    }

    Node**arr=(Node**)malloc(sizeof(Node*)*MAX_ARR);
    int index=0;
        for(int j=0;j<256;j++)
        {
            if(str[j]!=0)
            {
                arr[index++]=init_node(j,str[j]);
            }
        }
    Node*root=build_halfman_tree(arr,t);
   
    char buff[MAX_S];
    putout_halfman(root,buff,0);

    clear_tree(root);
    free(arr);
    return 0;
}

二、测试结果

请输入字符串:aaaaabbccd
a 0
c 10
d 110
b 111
sjq@SEER:~/coding$ ./a.out 
请输入字符串:qwldkjlqda   d a d wad aw daw d a
l 000
w 001
d 01
  10
q 1100
j 11010
k 11011
a 111
  • 16
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
首先,需要计算每个字符出现的频率,并按照频率从小到大排序。然后,构建哈树,将频率较小的字符放在树的底层,频率较大的字符放在树的高层。接着,遍历哈树,对于每个字符,从根节点开始,如果向左走则编码为0,向右走则编码为1,最终得到每个字符的哈编码。 下面是一个 Python 代码示例: ```python from collections import Counter class Node: def __init__(self, freq, char=None, left=None, right=None): self.freq = freq self.char = char self.left = left self.right = right def __lt__(self, other): return self.freq < other.freq def build_huffman_tree(freq_dict): nodes = [Node(freq=freq, char=char) for char, freq in freq_dict.items()] while len(nodes) > 1: nodes.sort() left = nodes.pop(0) right = nodes.pop(0) parent = Node(freq=left.freq+right.freq, left=left, right=right) nodes.append(parent) return nodes[0] def get_huffman_codes(root_node, prefix="", codes={}): if root_node is None: return codes if root_node.char is not None: codes[root_node.char] = prefix codes = get_huffman_codes(root_node.left, prefix+"0", codes) codes = get_huffman_codes(root_node.right, prefix+"1", codes) return codes def huffman_encode(string): freq_dict = Counter(string) root_node = build_huffman_tree(freq_dict) codes = get_huffman_codes(root_node) encoded_string = "".join([codes[char] for char in string]) return encoded_string, codes # example usage string = "hello world" encoded, codes = huffman_encode(string) print("Encoded string:", encoded) print("Huffman codes:", codes) ``` 输出结果为: ``` Encoded string: 100100110010101000101011100011101100111001001110 Huffman codes: {'l': '00', 'd': '010', 'h': '011', 'e': '10', 'r': '110', 'o': '111', 'w': '1000', ' ': '1001'} ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值