Build a version of the Unix uniq -u command. Given a list of lines, output only the values whose adjacent run length is exactly one — i.e. lines that did NOT repeat back-to-back. Surviving values are joined by \n.
Function signature:
fn uniq_once(lines: Vec<String>) -> String
Example:
Input: lines = ["a", "a", "b", "c", "c", "c"] Output: "b" When printed: b
The two "a"s and the three "c"s are dropped because their runs are longer than 1. Only the lone "b" survives.
Track a
String named prev and an integer count. When the line changes (or after the loop), flush prev only if count == 1.
if count == 1 {
result.push(prev.clone());
}
The full solution:
impl Solution {
fn uniq_once(lines: Vec<String>) -> String {
let mut result: Vec<String> = Vec::new();
let mut count = 0;
let mut prev = String::new();
for i in 0..lines.len() {
if count > 0 && lines[i] == prev {
count += 1;
} else {
if count == 1 {
result.push(prev.clone());
}
prev = lines[i].clone();
count = 1;
}
}
if count == 1 {
result.push(prev.clone());
}
return result.join("\n");
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
