Created
October 8, 2017 17:53
-
-
Save unilecs/6d8ba5998b7d05f08606aa55ba9f86ef to your computer and use it in GitHub Desktop.
Compression of string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function compressString(inputStr) { | |
if (inputStr) { | |
// частный случай: если строка состоит из 1го символа | |
// или сжатие приведет к увеличению строки | |
let length = inputStr.length, inputStrArr = [...inputStr]; | |
let compressStrLength = getCompressionStringLength(inputStrArr); | |
if (length === 1 || compressStrLength >= length) { | |
return inputStr; | |
} | |
let currentSymbol = inputStr[0], count = 0, result = ""; | |
inputStrArr.forEach((symbol, index) => { | |
if (symbol === currentSymbol) { | |
count++; | |
} | |
// если предыдущий символ не равен текущему ИЛИ итерация является последней | |
// то обнуляем счетчик | |
if (symbol !== currentSymbol || index === length - 1) { | |
result += currentSymbol + count; | |
count = 1; | |
currentSymbol = symbol; | |
} | |
}); | |
return result; | |
} | |
return ""; | |
} | |
// функция возвращает размер "сжатой" строки | |
function getCompressionStringLength(inputStrArr) { | |
let resultLength = 0, curSymbol = inputStrArr[0], count = 0; | |
inputStrArr.forEach((symbol, index) => { | |
if (curSymbol === symbol) { | |
count++; | |
} | |
// если предыдущий символ не равен текущему ИЛИ итерация является последней | |
// то обнуляем счетчик | |
if (curSymbol !== symbol || index === inputStrArr.length - 1) { | |
resultLength += 1 + count.toString().length; | |
curSymbol = symbol; | |
count = 1; | |
} | |
}); | |
return resultLength; | |
} | |
console.info("Compression of string: ", compressString("ZZZABBEEE")); // Z3A1B2E3 | |
console.info("Compression of string: ", compressString("abcca")); // abcca, т.к. после сжатия (a1b1c2a1) строка будет большего размера |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
const compressString = (string) => {
};