使用LZW算法对字符串进行压缩。
算法实现参考:
https://blog.csdn.net/qq_41819698/article/details/82558107
https://www.cnblogs.com/mcomco/p/10475329.html
js代码:
function compress(s){ var dic = {}; for(var i = 0; i < 256; i++){ var c = String.fromCharCode(i); dic[c] = c; } var prefix = ""; var suffix = ""; var idleCode = 256; var result = []; for(var i = 0; i < s.length; i++){ var c = s.charAt(i); suffix = prefix + c; if(dic.hasOwnProperty(suffix)){ prefix = suffix; } else { dic[suffix] = String.fromCharCode(idleCode); idleCode++; result.push(dic[prefix]); prefix = "" + c; } } if(prefix !== ""){ result.push(dic[prefix]); } return result.join(""); } function uncompress(s){ var dic = {}; for(var i = 0; i < 256; i++){ var c = String.fromCharCode(i); dic[c] = c; } var prefix = ""; var suffix = ""; var idleCode = 256; var result = []; for(var i = 0; i < s.length; i++){ var c = s.charAt(i); if(dic.hasOwnProperty(c)){ suffix = dic[c]; } else if(c.charCodeAt(0) === idleCode){ suffix = suffix + suffix.charAt(0); } else { } if(prefix !== ""){ dic[String.fromCharCode(idleCode)] = prefix + suffix.charAt(0); idleCode++; } result.push(suffix); prefix = suffix; } return result.join(""); }
compress用来压缩,uncompress用来解压。对于含有中文的字符串,可以先转成base64,再压缩。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。