Run Length Encode
Programming Interview
Medium
5 views
Problem Description
A string s is provided. Compress it using run-length encoding as: char followed by count (only when count>1). Output encoded string.
Input Format
One line s (no spaces).
Output Format
One line encoded.
Official Solution
import sys
s=sys.stdin.read().strip()
if not s: sys.exit(0)
out=[]
i=0
n=len(s)
while i<n:
j=i
while j<n and s[j]==s[i]:
j+=1
out.append(s[i])
cnt=j-i
if cnt>1:
out.append(str(cnt))
i=j
sys.stdout.write(''.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!