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.
Step 2: Loop through each character
for char in stringVal:
Goes through every character in the string one by one.
Step 3: Check if the character changes
if prevChar != char:
encodedList.append((prevChar, count))
count = 0
prevChar = char
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.
Step 4: Count occurrences
count = count + 1
Always increment the counter for the current character.
Step 5: Add the last group
encodedList.append((prevChar, count))
After the loop finishes, add the final character group to the list.
Step 6: Return result
return encodedList
The function returns the list of
(character, count) tuples.Microsoft Copilot
沒有留言:
發佈留言