Build a version of the Unix tr -s command. Given a list of lines and a string chars, collapse consecutive runs of any character that appears in chars to a single occurrence. Other characters are unchanged. Return the lines joined by newline characters (\n).
Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Only runs of the same character from chars are collapsed; all other characters, and runs of characters not in chars, stay as they are. Upper and lower case are different characters. Lines may be empty.
Function signature:
fn tr_squeeze(lines: Vec<String>, chars: String) -> String
Example:
Input: lines = ["aaabbb", "abaa"], chars = "a" Output: "abbb\naba" When printed: abbb aba
Collect every char of
chars into a HashSet<char>. Walk each line tracking prev (the last char you kept); skip the current char only if it's in the squeeze set AND equals prev.
The full solution:
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")
}
}
Free plan: 30 tutor messages. Premium is unlimited.
