The real cat command can take many files as arguments and prints them one after another. Build that behavior. Given a list of "files" where each file is itself a list of lines, flatten all lines in order and join them with newlines.
A file can be empty (it adds no lines), and the list can hold no files at all; the result is then an empty string.
Function signature:
string concatCat(vector<vector<string>> allLines)
Example:
Input: allLines = [["hello", "world"], ["foo", "bar", "baz"]] Output: "hello\nworld\nfoo\nbar\nbaz" When printed: hello world foo bar baz
Use a nested loop. Track whether you've emitted at least one line so you only insert
"\n" between lines, never before the first.
A
bool first = true; flag works well — set it to false after the first append, and only prepend the newline when !first.
if (!first) result += "\n";
result += allLines[i][j];
first = false;
The full solution:
class Solution {
public:
string concatCat(vector<vector<string>> allLines) {
string result;
bool first = true;
for (int i = 0; i < allLines.size(); i++) {
for (int j = 0; j < allLines[i].size(); j++) {
if (!first) result += "\n";
result += allLines[i][j];
first = false;
}
}
return result;
}
};
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
