例如 -
原文字符串:heeeeelllllloo
压缩:h1e5l6o2
解压缩:heeeeelllllloo
此代码以无限循环形式出现,问题出现在压缩函数中。请帮我找/解决问题!
这就是我到目前为止所做的:
// Read in the original text
var textToCompress = prompt("Enter the text you would like to compress: ");
runLengthEncoding(textToCompress);
function runLengthEncoding(originalText){
console.log("Original Text: " + originalText);
console.log("");
// Compress the text
console.log("COMPRESSING...");
var compressedText = compress(originalText);
console.log("Compressed: " + compressedText);
console.log("");
//Decompress the text
console.log("DECOMPRESSING...");
//var decompressedText = decompress(compressedText);
console.log("Decompressed: " + decompressedText);
console.log("");
// Make sure the compression was lossless
if(originalText == decompressedText)
{
console.log("Success! The decompressed text is the same as the original!");
}
}
// Compresses the original String by building up a new String
// with each character and how many times it repeats in a given run.
// Returns the compressed text.
function compress(original){
var result = "";
//Write your code here
for (var i = 1; i < original.length; i++){//look at each character in string
var sum = 1;
var currentChar = original.charAt(i);
//if currentchar is the first character
if (currentChar == original.charAt(0)){//isolate frist character of the string
result = currentChar;//add the currentchar to result
console.log(result);
//if currentchar is not the first character
} else if (currentChar !== original.charAt(0)) {
//if currentchar is equal to the previous character
if (currentChar == original.charAt(i-1)){
sum++;
} else {
result += sum;//add sum ot the result and reset sum to 1
sum = 1;
i = 0;
}
}
}
}
// Decompresses the compressed Run Length Encoded text back
// into the original form.
function decompress(compressedText)
{
var result = "";
for(var i = 0; i < compressedText.length; i += 2)
{
// Get the current run character
var character = compressedText.charAt(i);
// Get the run length
var runLength = parseInt(compressedText.charAt(i+1));
// Add that many repetitions of the original character to the result
for(var runIndex = 0; runIndex < runLength; runIndex++)
{
result += character;
}
}
return result;
}
答案 0 :(得分:0)
首先,不要比较字符以找出这个字符是否是第一个字符,因为如果在文本中重复第一个字符,这将返回true。
我看到的一件事是,每当你找到一个新的字符时,你就将索引i设置为0,这会导致你的函数再次从字符串的开头开始,并以死锁结束。
至少我的想法,我希望我可以帮助你