GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — coding-problems/Strings/encoding_string.py at master · onowdev/coding-problems Expand file tree/ Copy pathencoding_string.pyMore file actions 50 lines (37 loc) · 1.06 KB / Copy pathencoding_string.pyFile metadata and controls50 lines (37 loc) · 1.06 KB 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. |