Problem overview
Version 4 mirrors tr -s. tr_squeeze(lines, chars) collapses each run of the same character into a single character, but only for characters that appear in chars. Other characters, including repeated ones that are not in chars, are left as they are. The lines are joined by \n. The string chars is non-empty ASCII, characters are literal, case matters, and lines may be empty. The previous version deleted characters; this one keeps the first of each run.
For ["aaabbb", "abaa"] with "a", the result is "abbb\naba". The run aaa shrinks to a, the b run is untouched because b isn't in chars, and in abaa only the final aa shrinks.
Approach
A character is dropped only when two things are true: it is in the squeeze set, and it is the same as the character just before it in the output. So the loop needs a fast membership test (a HashSet) and the previous character (prev). Each line starts with prev set to '\0', the null character, which doesn't occur in ordinary text, so the first character of a line never counts as a repeat.
Because prev is updated after every kept character and a dropped one equals it anyway, prev always holds the last character written. A run of any length therefore reduces to its first character.
On "abaa" with "a": the first a is kept, because prev is still '\0'. The b is kept (not in the set). The next a is kept, because prev is now b. The last a equals prev and is in the set, so it is dropped. The result is "aba". On "aaabbb", the first a is kept, the next two are dropped, and all three b characters are kept because b isn't in the set, giving "abbb".
Step by step
- Build the set with
chars.chars().collect()into aHashSet<char>namedsqueeze. The type on the left tellscollectwhat to build. - Create
result, an emptyVec<String>. - Loop over the lines with
for line in &lines. - Create
out, a freshStringfor each line. - Create
prevas'\0', since nothing precedes the first character. - Loop over the characters with
line.chars(). - Test for a repeat:
squeeze.contains(&ch) && ch == prev. - Skip the character with
continue, which jumps straight to the next one. - Otherwise push
chontoout. - Set
prevtoch, so the next character compares against this one. - Push
outontoresultafter the inner loop. An emptied line stays as an empty line. - Join with
"\n"as the function's last expression.
The solution in Rust
impl Solution {
fn tr_squeeze(lines: Vec<String>, chars: String) -> String {
let squeeze: HashSet<char> = chars.chars().collect();
let mut result: Vec<String> = Vec::new();
for line in &lines {
let mut out = String::new();
let mut prev = '\0';
for ch in line.chars() {
if squeeze.contains(&ch) && ch == prev {
continue;
}
out.push(ch);
prev = ch;
}
result.push(out);
}
result.join("\n")
}
}
Rust details:
collectneeds a target type. It can build many collections, so the annotationHashSet<char>decides which one. In a standalone program, adduse std::collections::HashSet;.- The
'\0'literal. It is achar, the character with code 0. Its type is fixed by the first use ofprevin a comparison withch. continuein the inner loop. It skips the rest of that iteration only, so neither the push nor the update ofprevruns for a dropped character. The outer loop is not affected.- Last-expression return.
result.join("\n")has no semicolon and noreturn, so it is the function's value.
Notice that a dropped character never changes prev, because continue jumps over that line. That is correct, since a dropped character is equal to prev already, so the value would not change anyway.
Complexity
Time: O(C + L), where C is the length of chars and L the total length of the lines: building the set, then one pass with average-constant-time lookups. Space: O(C + L) for the set, the output lines and the joined string.
Edge cases and common mistakes
- Only listed characters are squeezed.
["aabbcc", "a b c"]with"ab "gives"abcc\na b c". Thea,band space runs shrink, butccstays becausecisn't listed. - Case.
["aAaa"]with"a"gives"aAa". Only the finalaais a run, asAis a different character and breaks the run. - Alternating characters.
["abab"]with"ab"gives"abab", since no character equals the one just before it. - Empty lines.
["", "zz"]with"a"gives"\nzz": the empty line stays and thezrun isn't squeezed. - The null character itself. The sentinel only works because
'\0'isn't expected in the text. If a line did start with a null character andcharscontained one, that first character would be treated as a repeat and dropped:"\0\0x"with the set"\0"comes out as just"x". The task's lines are ordinary ASCII text, so it doesn't arise. - Comparing with the wrong character.
prevmust be updated after every kept character, listed or not. Otherwise the comparison for the next character would look at a stale value. - Carrying
prevacross lines. It is created inside the line loop, so a line's first character is never compared with the previous line's last.
Testing
["aaabbb", "abaa"]with"a"gives"abbb\naba".["aabbcc", "a b c"]with"ab "gives"abcc\na b c".["aAaa"]with"a"gives"aAa".["", "zz"]with"a"gives"\nzz".
