Same signature as v2, but now n may be larger than the number of lines. If n > lines.len() 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:
fn head(lines: Vec<String>, n: i32) -> String
Example:
Input: lines = ["alpha", "beta", "gamma"], n = 10 Output: "alpha\nbeta\ngamma" When printed: alpha beta gamma
Slicing
lines[0..n] past the end panics in Rust, so clamp n with (n as usize).min(lines.len()) before slicing. Rust's [T]::join then stitches the prefix together with newlines.
let end = (n as usize).min(lines.len());
return lines[0..end].join("\n");
The full solution:
impl Solution {
fn head(lines: Vec<String>, n: i32) -> String {
let end = (n as usize).min(lines.len());
return lines[0..end].join("\n");
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
