Build a tiny version of the Unix cat command. Given a list of lines, return them joined by newline characters (\n) so they print one per line.
Lines can be blank, and the list can be empty (the result is then an empty string).
Function signature:
string cat(vector<string> lines)
Example:
Input: lines = ["hello", "world", "foo"] Output: "hello\nworld\nfoo" When printed: hello world foo
C++'s standard library has no built-in
join, so you'll build the result manually. Walk through the lines and accumulate them into a single string, inserting a "\n" between every pair.
A clean trick: only prepend
"\n" when i > 0. That way the first line has no separator before it, and every subsequent line is preceded by exactly one newline.
string result;
for (int i = 0; i < lines.size(); i++) {
if (i > 0) result += "\n";
result += lines[i];
}
The full solution:
class Solution {
public:
string cat(vector<string> lines) {
string result;
for (int i = 0; i < lines.size(); i++) {
if (i > 0) result += "\n";
result += lines[i];
}
return result;
}
};
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
