Same signature as v2, but now n may be larger than the number of lines. If n > lines.size() simply return all the lines (don't crash, don't pad). For this version assume n ≥ 0. If n is 0, or there are no lines, the result is the empty string.
Function signature:
string head(vector<string> lines, int n)
Example:
Input: lines = ["alpha", "beta", "gamma"], n = 10 Output: "alpha\nbeta\ngamma" When printed: alpha beta gamma
Indexing
lines[i] past the end is undefined behavior in C++, so clamp n with min((int)lines.size(), n) before the loop.
int end = min((int)lines.size(), n);
for (int i = 0; i < end; i++) {
if (i > 0) result += "\n";
result += lines[i];
}
The full solution:
class Solution {
public:
string head(vector<string> lines, int n) {
int end = min((int)lines.size(), n);
string result;
for (int i = 0; i < end; i++) {
if (i > 0) result += "\n";
result += lines[i];
}
return result;
}
};
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
