Build a version of the Unix uniq -d command. Given a list of lines, output only the values whose adjacent run length is greater than one — i.e. lines that actually repeat back-to-back. Each surviving value is printed once (no count, just the value), joined by \n.
Function signature:
string uniqDups(vector<string> lines)
Example:
Input: lines = ["a", "a", "b", "c", "c", "c"] Output: "a\nc" When printed: a c
The run of "a"s has length 2 and the run of "c"s has length 3, so both survive. The single "b" is dropped.
Track
string prev and int count. When the line changes (or after the loop), flush prev only if count > 1. After collecting the survivors, join with "\n".
if (count > 1) {
result.push_back(prev);
}
The full solution:
class Solution {
public:
string uniqDups(vector<string> lines) {
vector<string> result;
int count = 0;
string prev = "";
for (int i = 0; i < lines.size(); i++) {
if (count > 0 && lines[i] == prev) {
count++;
} else {
if (count > 1) {
result.push_back(prev);
}
prev = lines[i];
count = 1;
}
}
if (count > 1) {
result.push_back(prev);
}
string out;
for (int i = 0; i < result.size(); i++) {
if (i > 0) out += "\n";
out += result[i];
}
return out;
}
};
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
