LZW压缩算法js版

本文介绍了一种基于哈希表的字符串压缩与解压算法实现。该算法通过构建哈希表来提高搜索效率,并采用逐步更新的方法进行字符串解压缩,能够有效地处理输入文本并还原其原始内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. function Decompress(srctext){  
  2.     var ht          = new Array;
  3.     var used            = 128;
  4.     var intLeftOver         = 0;
  5.     var intOutputCode       = 0;
  6.     var ccode           = 0;
  7.     var pcode       = 0;
  8.     var key             = 0;
  9.     var Outbuff     = "";
  10.     for(var i=0;i <used;i++){ ht[i] = String.fromCharCode(i);}
  11.     for(i=0;i<srctext.length;i++){
  12.         intLeftOver     += 16;
  13.         intOutputCode   <<= 16;
  14.         intOutputCode   |= srctext.charCodeAt(i);
  15.         while(1){
  16.             if(intLeftOver >= 12){
  17.                 ccode = intOutputCode >> (intLeftOver - 12);
  18.                 iftypeof( key = ht[ccode] ) != "undefined"){
  19.                     Outbuff += key;
  20.                     if(used > 128){
  21.                         ht[ht.length] = ht[pcode] + key.substr(0, 1);
  22.                     }
  23.                     pcode = ccode;
  24.                 }else{
  25.                     key = ht[pcode] + ht[pcode].substr(0, 1);
  26.                     Outbuff += key;
  27.                     ht[ht.length] = ht[pcode] + key.substr(0, 1);
  28.                     pcode = ht.length - 1;
  29.                 }
  30.                 used ++;
  31.                 intLeftOver -= 12;
  32.                 intOutputCode &= (Math.pow(2,intLeftOver) - 1);
  33.             }else{break;}
  34.         } 
  35.     } 
  36.     return Outbuff;
  37. }
  38. function HashTableElement(k,c){
  39.     this.key = k;
  40.     this.code = c;
  41. }
  42. function HashTable(){
  43.     this.ht = new Array(4099);
  44.     this.Search = function(keyword){
  45.         var arr = this.ht[keyword % 4099];
  46.         if(typeof(arr) != "undefined"){
  47.             for(i = 0; i < arr.length; i ++){
  48.                 if(arr[i].key == keyword) 
  49.                     return arr[i].code;
  50.             }
  51.         }
  52.         return null;
  53.     }
  54.     this.Insert = function(lKey,lCode){
  55.         var e   = new HashTableElement(lKey,lCode); 
  56.         if(typeof this.ht[e.key % 4099] == "undefined"){
  57.             this.ht[e.key % 4099]   = []; 
  58.         } 
  59.         this.ht[e.key%4099].push(e); 
  60.     }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值