Problem overview
The fourth version of tr behaves like tr -s. trSqueeze(_ lines: [String], _ chars: String) -> String collapses each run of the same character into a single character, but only for characters that appear in chars. Everything else is unchanged, and the lines are joined with "\n". chars is non-empty ASCII, taken literally, and case matters.
For ["aaabbb", "abaa"] and "a" the result is "abbb\naba". The run of a at the start of the first line shrinks to one a, but the b run is not in chars, so it stays whole.
Approach: skip a character that repeats the one just kept
A run is squeezed by keeping its first character and skipping the rest. So while scanning a line, compare each character with the last one you kept, prev. A character is skipped only when both conditions hold: it is in chars, and it equals prev. Otherwise it is appended to the output and becomes the new prev.
The test for membership uses a Set<Character>, as the previous version did for deletion. What changes is the extra memory of the last kept character.
Here is the idea on "aabbaa" with chars = "a". The second a repeats the first, so it goes. The two b characters stay, because b is not in the set. The last two a characters are a new run, so one goes. The result is "abba".
Tracing "aabbaa" with chars = "a" character by character gives:
| Character | Decision | Output so far |
|---|---|---|
a | kept | a |
a | skipped | a |
b | kept | ab |
b | kept | abb |
a | kept | abba |
a | skipped | abba |
The second b is kept even though it equals prev, because b is not in the set. The fifth character is kept because the last kept character was b, so a new run of a begins.
Each line starts over with a fresh sb and a fresh prev, so a run never continues across a line break. With ["a", "a"] and "a" the answer is "a\na": two lines, each holding one a, not one a in total. The same holds when a line ends and the next one begins with the same character: ["xaa", "aax"] gives "xa\nax".
Step by step
- Create
squeezeas an emptySet<Character>withvar. - Loop over each
chinchars. - Insert
chintosqueeze. Duplicates incharsare absorbed by the set. - Create
result, an empty[String]. - Loop over each
lineinlines. - Create
sb, an empty string, to hold the characters this line keeps. - Create
prevas aCharacterset to"\0", the null character. At the start of a line nothing has been kept, soprevstarts as a character that does not occur in the lines. - Loop over each
chinline. - Test
squeeze.contains(ch) && ch == prev. Both must be true to skip a character. - Write
continueinside that test. It jumps to the next character, so this one is never appended. - After the test, append
chtosb. The first character of a run always gets here. - Set
prev = ch.previs always the last character kept. - Append
sbtoresultafter the inner loop. A line may come out empty, and it still goes in. - Return the joined lines after the outer loop.
The solution in Swift
class Solution {
func trSqueeze(_ lines: [String], _ chars: String) -> String {
var squeeze = Set<Character>()
for ch in chars {
squeeze.insert(ch)
}
var result = [String]()
for line in lines {
var sb = ""
var prev: Character = "\0"
for ch in line {
if squeeze.contains(ch) && ch == prev {
continue
}
sb.append(ch)
prev = ch
}
result.append(sb)
}
return result.joined(separator: "\n")
}
}
Details that matter:
- A
Characterliteral."\0"is a double-quoted literal, but the annotation: Charactermakes it a single character instead of a string. Without the annotation, Swift would inferString, andch == prevwould no longer compile. - Why a sentinel. The null character stands for "nothing kept yet". Since the lines hold ordinary text, no real character equals it, so the first character of every line is kept.
continue. It ends the current pass of the inner loop only. The outer loop and the remaining characters of the line are unaffected.&&short-circuits. If the first test,squeeze.contains(ch), is false, Swift doesn't evaluate the second.prevfollows kept characters. Thecontinuejumps overprev = ch, soprevchanges only when a character is kept. A skipped character equalsprevanyway, so nothing is lost.
Complexity
Time: O(k + m), for k characters in chars and m characters across all lines: each line character costs one set lookup, one comparison and at most one append. Space: O(k + m) for the set and the output.
Edge cases and common mistakes
- Only runs of the same character collapse.
["ababab"]with"ab"returns"ababab", because no character repeats directly after itself. - Characters outside
charsare never squeezed.["aabbaa"]with"a"returns"abba": thebbstays. - Several characters at once.
["aabbcc"]with"ab"returns"abcc". Theaandbruns shrink; thecrun does not. - Spaces.
["a b c"]with a single space ascharsreturns"a b c". - Case.
["aAaA", "AAaa"]with"a"returns"aAaA\nAAa". In the second line the two uppercase letters are not in the set, and the lowercase pair squeezes to one. - Empty lines.
["", "x"]with"x"returns"\nx". - Skipping with the wrong test. Testing only
ch == prevwould squeeze every run, includingbbbin the example, which should stay.
Testing
["aaabbb", "abaa"],"a"gives"abbb\naba".["aabbaa"],"a"gives"abba".["aabbcc"],"ab"gives"abcc".["a b c"]," "gives"a b c".["aAaA", "AAaa"],"a"gives"aAaA\nAAa".["", "x"],"x"gives"\nx".
