GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — coding-problems/Strings/encoding_string.py at master · C2c-oops/coding-problems

Expand file tree

/

encoding_string.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
50 lines (37 loc) · 1.06 KB
/

encoding_string.py

Copy path

File metadata and controls

50 lines (37 loc) · 1.06 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
'''
Encoding string
Run-length encoding is a fast and simple method of encoding strings.
The basic idea is to represent repeated successive characters as a single count and character.
Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters.
You can assume the string to be decoded is valid.
Input: 'AAAABBBCCDAA'
Output: '4A3B2C1D2A'
=========================================
Simple solution, just iterate the string and count.
Time Complexity: O(N)
Space Complexity: O(1)
'''
############
# Solution #
############
def encoding(word):
n = len(word)
if n == 0:
return ''
letter = word[0]
length = 1
res = ''
for i in range(1, n):
if word[i] == letter:
length += 1
else:
res += str(length) + letter
letter = word[i]
length = 1
res += str(length) + letter
return res
###########
# Testing #
###########
# Correct result => '4A3B2C1D2A'
print(encoding('AAAABBBCCDAA'))
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.