Problem overview
The third wc version combines the line, word and character counts behind one function: wc(lines: Vec<String>, mode: String) -> String. The mode says which count to return, and the result is always text:
"l"returns the number of lines."w"returns the number of words."c"returns the number of characters, with no newlines counted."all"returns the three counts in the order lines, words, characters, separated by tab characters.
Any other mode gives the same result as "all", and modes are case-sensitive, so "L" is not "l". For lines = ["hello", "world"] and mode = "all" the result is "2\t2\t10": 2 lines, 2 words and 10 characters.
Approach: count everything once, then pick
The earlier versions each counted one thing. Here the simplest design computes all three counts first and lets the mode choose which one to return. That needs only a single pass over the lines, and the choice at the end is a few if statements.
- The line count needs no loop: it is
lines.len(). - The word count adds
split_whitespace().count()for each line, as in the word version. - The character count adds
chars().count()for each line. The previous version usedlen(), which counts bytes.chars()walks the string by characters, so the count is right for any text. The two agree on ASCII.
The order of the final checks matters. The three specific modes return early, and the last line, which builds the tab-separated text, runs for everything else. That is how "all", "x" and "L" all end up with the same result without being listed one by one.
The cost of this design is that all three counts are computed even when the caller wants only one. That is fine for a tool whose time stays linear anyway, and it keeps the code short: the branching happens in one place, after the counting, instead of being mixed into the loop.
Step by step
- Store the line count.
let num_lines = lines.len();is all it takes, and it doesn't change afterwards, so nomutis needed. - Create the word total as
let mut num_words = 0;, because it grows as lines are read. - Create the character total the same way, as
let mut num_chars = 0;. - Loop over the lines by reference with
for line in &lines, so the vector is borrowed and stays usable. - Add the words of this line with
split_whitespace().count(). A blank line adds nothing. - Add the characters of this line with
chars().count(). Spaces count, since they are part of the line. - Return the line count for
"l".to_string()turns the number into aString, because the function always returns text. - Return the word count for
"w"in the same way. - Return the character count for
"c"in the same way. - Return all three counts as the last line.
format!builds aStringfrom a template in which each{}takes the next value, and\tin the template is a tab character.
The solution in Rust
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);
}
}
Rust details worth knowing:
- No casts this time. All three counts stay
usize:len()andcount()both return it, and the compiler infers that type for the twolet muttotals. Since the function returns text, nothing needs to be converted toi32. - Comparing a
Stringwith a literal.mode == "l"compares aStringwith a&strby content. It doesn't compare addresses. to_string()andformat!. Integers implementto_string(), which gives their decimal digits.format!works likeprintln!, but it returns the text instead of printing it.- Why
mutonly on two of them.num_linesis set once and never changes, whilenum_wordsandnum_charsare updated on every pass of the loop. Rust makes a variable immutable unless you say otherwise, which tells the reader which values change. - Early returns. After a
returninside anif, the function stops there. Code below runs only when no earlier branch matched.
Complexity
Time: O(m), where m is the total number of characters in all lines. Each line is scanned twice, once by split_whitespace() and once by chars(), which is still linear.
Space: O(1) beyond the returned string. The counters are integers, and the result holds a handful of digits.
Edge cases and common mistakes
- Empty list. The loop never runs.
"l","w"and"c"each give"0", and"all"gives"0\t0\t0". - Unknown or differently cased modes.
"x"and"L"fall through to the last line and give the same text as"all". Don't add a branch that rejects them. - Returning numbers. The function returns a
String. Writingreturn num_lines;is a type error, so convert it withto_string(). - A blank line is still a line. For
["a b c", "", " x"]the line count is 3, even though the middle line has no words. The word count is 4 and the character count is 9. - Counting the separators. As in the previous version, newlines between lines are not part of the character count.
- Wrong order in the tab-separated result. It is lines, then words, then characters.
Testing
Here are inputs with the results the function returns, written as Rust string literals:
["hello", "world"]with"all"gives"2\t2\t10".["hello", "world"]with"l"gives"2", with"w"gives"2"and with"c"gives"10".["hello", "world"]with"x"or"L"gives"2\t2\t10".["a b c", "", " x"]with"all"gives"3\t4\t9".- An empty vector with
"all"gives"0\t0\t0".
