Combine the previous three versions of wc. Given a list of lines and a mode flag, return the requested count(s) as a string. This is our own simplified interface, not the real wc flags: the real tool combines flags (such as -lw) and pads its columns with spaces.
Function signature:
fn wc(lines: Vec<String>, mode: String) -> String
Mode values:
"l"→ line count, as a string."w"→ word count (whitespace-separated tokens), as a string."c"→ character count (lines only, no separating newlines), as a string."all"→lines + "\t" + words + "\t" + chars.
The "c" count is the one from v3 (the sum of the line lengths, no newlines). Any other mode value, for example "x" or "L" (modes are case-sensitive), gives the same result as "all". For an empty list, "l", "w" and "c" give "0" and "all" gives "0<TAB>0<TAB>0". The input is plain ASCII text.
Example:
Input: lines = ["hello", "world"], mode = "all" Output: "2\t2\t10"
2 lines, 2 words (one per line), 10 characters total.
Compute all three counts in a single pass through
lines, then branch on mode to pick the return value. split_whitespace() handles the word count for you.
let num_lines = lines.len();
let mut num_words = 0;
let mut num_chars = 0;
for line in &lines {
num_words += line.split_whitespace().count();
num_chars += line.chars().count();
}
Use .to_string() to convert numbers to strings.
The full solution:
impl Solution {
fn wc(lines: Vec<String>, mode: String) -> String {
let num_lines = lines.len();
let mut num_words = 0;
let mut num_chars = 0;
for line in &lines {
num_words += line.split_whitespace().count();
num_chars += line.chars().count();
}
if mode == "l" { return num_lines.to_string(); }
if mode == "w" { return num_words.to_string(); }
if mode == "c" { return num_chars.to_string(); }
return format!("{}\t{}\t{}", num_lines, num_words, num_chars);
}
}
Free plan: 30 tutor messages. Premium is unlimited.
