Run-Length Encode
JavaScript
Medium
7 views
Problem Description
Given a string, compress it using run-length encoding: aaaabb -> a4b2. Print encoded string.
Input Format
One line string.
Output Format
One line encoded string.
Constraints
Length up to 2e5.
Official Solution
const fs=require('fs');const s=fs.readFileSync(0,'utf8').trim();if(!s){process.stdout.write('');process.exit(0);}let out=[];let cur=s[0],cnt=1;for(let i=1;i<s.length;i++){if(s[i]===cur)cnt++;else{out.push(cur+String(cnt));cur=s[i];cnt=1;}}out.push(cur+String(cnt));process.stdout.write(out.join(''));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!