Decode Simple RLE
Python
Medium
3 views
Problem Description
Read string like a2b3c1 meaning aa bbb c. Output decoded string. If format is invalid (missing count or non-digit count), output ERROR.
Input Format
One line rle string.
Output Format
Decoded string or ERROR.
Official Solution
import sys
s=sys.stdin.read().strip()
if not s:
sys.stdout.write('')
raise SystemExit
out=[]
i=0
n=len(s)
try:
while i<n:
ch=s[i]
if ch.isdigit():
raise ValueError()
i+=1
if i>=n or not s[i].isdigit():
raise ValueError()
cnt=0
while i<n and s[i].isdigit():
cnt=cnt*10+(ord(s[i])-48)
i+=1
if cnt<0:
raise ValueError()
out.append(ch*cnt)
sys.stdout.write(''.join(out))
except Exception:
sys.stdout.write('ERROR')
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!