def encodeString(stringVal):
encodedList = []
prevChar = stringVal[0]
count = 0
for char in stringVal:
if prevChar != char:
encodedList.append((prevChar, count))
count = 0
prevChar = char
count = count + 1
encodedList.append((prevChar, count))
return encodedList
Step 1: Setup
encodedList = []→ empty list to store results.prevChar = stringVal[0]→ start with the first character of the string.count = 0→ counter for consecutive occurrences.
If the current character is different from the previous one:
Save the previous character and its count into
encodedList.Reset
countto 0.Update
prevCharto the new character.
When you hit a character change, you first append the tuple
(prevChar, count)toencodedList.At that moment, the value of
countis already finalized for that run (e.g., 3 for'a').That tuple is stored in the list and won’t be touched againAfter saving, you reset
count = 0because you’re about to start counting a new run for the next character.This reset only affects future counting, not the already-saved tuple.
(character, count) tuples.Take "aaabbc" as input:
Start:
prevChar = 'a',count = 0Loop:
'a'→ same asprevChar→count = 1'a'→ same →count = 2'a'→ same →count = 3'b'→ different!Save
('a', 3)Reset
count = 0Update
prevChar = 'b'Then increment →
count = 1
'b'→ same →count = 2'c'→ different!Save
('b', 2)Reset
count = 0Update
prevChar = 'c'Then increment →
count = 1
End of loop → Save
('c', 1)
Result: [('a', 3), ('b', 2), ('c', 1)]
沒有留言:
發佈留言