Loading...
Loading...
A school stores attendance as a string of capital letters, such as PPPAAP (P for present, A for absent, L for late). To save space, each run of the same letter is written as the letter followed by the length of the run.
For example, PPPAAP becomes P3A2P1. Print the compressed form of the given string.
Example 1
Input
PPPAAP
Output
P3A2P1
Three P, two A, then one P.
Example 2
Input
A
Output
A1
A single letter still gets its count.
Try the problem first. Open one hint at a time.
Walk through the string and count how long the current run is.
When the next letter is different (or the string ends), write the letter and its count.
Do not forget the last run: the loop ends before you see a "different" letter for it.
Build the answer with StringBuilder; += on a String in a loop is slow for 10^5 letters.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor