- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Encoding string to reduce its size in JavaScript
Problem
We are required to write a JavaScript function that takes in a string of characters, str, as the only argument. Our function should encode the input string and compare its size with the original string and return the string which is smaller in size.
The rule to encode a particular string is −
n[s], where the s inside the square brackets is being repeated exactly k times.
For instance, ddd can be encoded to 3[d] but 3[d] has a length of 4 whereas ddd is only 3 characters long so our function should eventually return ddd.
For example, if the input to the function is −
const str = 'aabcaabcd';
Then the output should be −
const output = '2[aabc]d';
Example
The code for this will be −
const str = 'aabcaabcd'; function encode(s) { const { length } = s; const dp = Array(length).fill([]); dp.forEach((el, ind) => { dp[ind] = Array(length).fill(null); }); for(let l = 1; l <= length; l++){ for(let i = 0; i + l <= length; i++){ let j = i + l - 1; dp[i][j] = s.substring(i, j + 1); for (let k = i; k < j ; k ++) { let acc = dp[i][k] + dp[k + 1][j]; if (acc.length < dp[i][j].length) { dp[i][j] = acc; } } let sub = s.substring(i, j + 1); let double = sub + sub; let cut = double.indexOf(sub, 1); if (cut != -1 && cut < sub.length) { let acc = sub.length / cut + "[" + dp[i][i + cut - 1] +"]"; if (acc.length < dp[i][j].length) { dp[i][j] = acc; } } } } let res = dp[0][dp.length - 1]; return res; } console.log(encode(str));
Output
And the output in the console will be −
2[aabc]d
- Related Articles
- Encoding string based on character frequency in JavaScript
- Query-string encoding of a Javascript Object
- Encoding a number string into a string of 0s and 1s in JavaScript
- Reduce Array Size to The Half in C++
- Encoding decimal to factorial and back in JavaScript
- How to reduce arrays in JavaScript?
- How to Split large string in to n-size chunks in JavaScript?
- How to reduce an array while merging one of its field as well in JavaScript
- Reduce 3: 2 to its simplest form.
- Reduce array in JavaScript
- Reduce the fraction to its lowest form in C++
- Reduce an array to groups in JavaScript
- PHP – Convert a string to a requested character encoding using iconv()
- How to decrease size of a string by using preceding numbers - JavaScript?
- Update column size in MySQL and increase its size?

Advertisements