Im gonna use python3 for this example
def encode(string):
if not string:
return string
new_string = []
last_char = ""
count = 1
for char in string:
if char == last_char:
new_string.pop(len(new_string)-1)
count += 1
elif char != last_char and count > 1:
new_string.append(str(count)+last_char)
count = 1
new_string.append(char)
last_char = char
else:
last_char = char
new_string.append(char)
return "".join(new_string)
print(encode("Hello There"))