Problem overview
The fourth version of the tr tool mimics tr -s. The method trSqueeze receives a list of lines and a string chars. In every line, a run of the same character that appears in chars collapses to a single occurrence. Other characters, and runs of characters not in chars, stay as they are. The lines are returned joined by "\n".
For ["aaabbb", "abaa"] and chars = "a", the result is "abbb\naba": the run of as becomes one a, while bbb is untouched, because b is not in chars. The characters are literal, case matters, and lines may be empty.
Approach: skip a character that repeats the last kept one
The earlier versions had a built-in string method to lean on. Here there is none, so the loop walks each line character by character and builds the output itself. It remembers the last character that was kept, prev. A character is skipped when two things are both true: it is one of the squeeze characters, and it equals prev. Anything else is kept.
The squeeze characters go into a set. A set answers "is this character one to squeeze?" in constant time, and set(chars) takes each character of the string as one member.
The state for one line is tiny: the list out and the single character prev. For "aaabbb" with chars = "a", the first a is kept and the next two equal prev and are skipped. Then each b is kept, because b is not in the set, so "aaabbb" becomes "abbb". A line made of only as, such as "aaaa", collapses to a single "a", not to an empty string.
Step by step
- Create
squeeze = set(chars). - Create an empty list
resultfor the finished lines. - Write the outer
forloop,linetaking each line oflines. - Inside it, create a fresh empty list
outfor the characters this line keeps. It must be new for each line, or the lines would mix. - Also inside it, create
prev = ''. At the start of a line nothing came before, so it starts empty. - Write an inner
forloop,chtaking each character ofline. - Inside, write
if ch in squeeze and ch == prev:and, in its body,continue. This jumps to the next character, so this one is never added. - After the
if, still in the inner loop, appendchtooutand setprev = ch. The first character of a run is kept; only the repeats are dropped. - After the inner loop, append
''.join(out)toresult. This runs once per line, so it sits outside the inner loop. - After the outer loop, return
"\n".join(result).
The solution in Python
class Solution:
def trSqueeze(self, lines, chars):
squeeze = set(chars)
result = []
for line in lines:
out = []
prev = ''
for ch in line:
if ch in squeeze and ch == prev:
continue
out.append(ch)
prev = ch
result.append(''.join(out))
return "\n".join(result)
Some details:
- Looping over a string hands out one character at a time, each as a string of length 1.
prevholds the last character kept. Because skipped characters equalprevanyway, it is also the previous character of the original line.- Starting
prevas''is safe, because no real character equals the empty string, so the first character of a line is never skipped. - Two
joincalls with different separators do two different jobs:''.join(out)builds one line from its characters, and"\n".join(result)builds the answer from the lines.
Complexity
Every character is visited once with constant work: a set lookup, a comparison and an append. The total time is linear in the number of characters in all lines, plus the size of chars to build the set. The lists out and result need extra space of the same order.
Edge cases and common mistakes
| lines | chars | result |
|---|---|---|
["aaabbb", "abaa"] | "a" | "abbb\naba" |
["aaabbb"] | "ab" | "ab" |
["aabbaa"] | "a" | "abba" |
["", " x y"] | " " | "\n x y" |
["aaabbb"] | "c" | "aaabbb" |
- In the third row the two runs of
aare separate, withbbbetween them, and each collapses on its own. - In the fourth row the empty line stays empty and keeps its place, and each run of spaces becomes one space.
- Only runs of the same character collapse. In the second row,
aandbare both squeezed, butaaabbbbecomesabbecause each run collapses separately;abis not treated as one run. - The
continuecould be replaced by putting the append and the update ofprevin anelsebranch. Both forms do the same thing;continuekeeps the two lines that are always executed for a kept character at the same indent as the loop body. - Forgetting to reset
outandprevfor each line carries state from one line into the next. - Updating
prevonly when the character is insqueezeis a bug. Withchars = "a", the line"aba"then becomes"ab": thebdoesn't updateprev, so the lastais compared with the first one and wrongly skipped. Setprevfor every character that is kept, so that only truly adjacent repeats are dropped. - Squeezing is not the same as removing duplicates: with
chars = "ab", the line"aabbab"becomes"abab", because theaandbthat alternate are not repeats of each other.
