Problem overview
This version combines the previous three counters in one function, wc, which takes a vector<string> of lines and a string named mode, and returns the requested count as text. The modes are:
"l": the number of lines;"w": the number of words, split on whitespace;"c": the number of characters, the sum of the line lengths with no newlines;"all": the line, word and character counts joined by tab characters.
Any other mode, such as "x" or "L" (modes are case-sensitive), gives the same result as "all". This is the lesson's own simplified interface, not the flags of the real tool.
For ["hello", "world"] with mode "all" the result is "2\t2\t10": 2 lines, 2 words and 10 characters. For an empty vector, "l", "w" and "c" each give "0", and "all" gives "0\t0\t0".
Approach: count everything once, then choose
Each count is already known from the earlier versions. The simplest way to combine them is to compute all three in a single pass over the lines and decide at the end which one to return. That is cheap, because all three counts are quick to get, and it keeps the loop free of mode checks.
The line count needs no loop at all: it is the size of the vector. The word count uses an istringstream per line and counts successful reads with >>. The character count adds the size of each line. The two loop-based counts share one loop.
The choice comes last, as a chain of if statements that each return. The last line is not guarded by any condition. Every mode that is not "l", "w" or "c" reaches it, so "all" and every unknown mode share the same result without a special case.
Step by step
- Store the line count in
numLines. It islines.size(), so no loop is needed for it. - Create
numWordsas anintset to 0. It grows while the loop reads lines. - Create
numCharsthe same way. - Loop over the lines by position with
ifrom 0 whilei < lines.size(). - Make an
istringstreamnamedssfromlines[i]. It will hand out the line's words one at a time. - Create a
stringnamedwordto receive each word. - Count the words with a single-statement
while (ss >> word)that adds 1 tonumWords. A blank line fails the first read and adds nothing. - Add
lines[i].size()tonumCharsbefore the loop ends. The characters come from the whole line, spaces included. - Return the line count as text for mode
"l". The function returns astring, so theintgoes throughto_stringfirst. - Do the same for
"w"with the word count. - And for
"c"with the character count. - Return the three counts joined by tabs on the last line, in the order lines, words, characters. Each number goes through
to_string, and the pieces are joined with+.
The solution in C++
class Solution {
public:
string wc(vector<string> lines, string mode) {
int numLines = lines.size();
int numWords = 0;
int numChars = 0;
for (int i = 0; i < lines.size(); i++) {
istringstream ss(lines[i]);
string word;
while (ss >> word) numWords++;
numChars += lines[i].size();
}
if (mode == "l") return to_string(numLines);
if (mode == "w") return to_string(numWords);
if (mode == "c") return to_string(numChars);
return to_string(numLines) + "\t" + to_string(numWords) + "\t" + to_string(numChars);
}
};
The C++ details worth a closer look:
to_stringconverts numbers to text.to_string(42)is"42". You can't add anintto astringwith+directly, which is why every number is converted first.- Joining with
+works on astringand a literal.to_string(numLines) + "\t"is astringplus a character array, which C++ accepts because the left side is already astring. Two plain literals,"a" + "b", would not compile. - Comparing strings with
==. Forstringvalues,mode == "l"compares the contents, so it works as you would hope. The comparison is exact:"L"is not"l". - A braceless
whileand one-lineifs. A single statement doesn't need braces. The lesson uses that style for the word counter and for the three early returns, and it works only because each body is exactly one statement. - Order of the checks. The early returns are independent, so their order among
"l","w"and"c"doesn't matter. The unguarded return has to come last.
Complexity
Time: O(total length). The loop reads each line once for the words, and size() takes constant time. Building the answer string is proportional to the number of digits, which is tiny. The by-value vector parameter also costs a copy proportional to the total length.
Space: O(total length) in this version, mostly from that copy. Besides it, the code uses three integers and the stream for one line.
Edge cases and common mistakes
- Empty vector. With an empty vector, mode
"l"gives"0"and mode"all"gives"0\t0\t0", because every count starts at 0 and the loop doesn't run. - Unknown modes. For
["hello world", "foo bar baz", ""], both"L"and"x"give"3\t5\t22", the same as"all". - Returning a number. The function returns text. Writing
return numLines;doesn't compile, because anintdoesn't convert to astring. - The order in
"all". It is lines, words, characters, with a tab between each pair and no tab at the end. - Counting newlines as characters. The character count is the sum of the line lengths, so
["hello", "world"]has 10 characters, not 11. - Blank lines. They count as lines and add 0 words and 0 characters. The empty third line of the example is why there are 3 lines but only 5 words.
Testing
Results are the function's return values, with tabs written as \t. With lines = ["hello world", "foo bar baz", ""]:
- mode
"l"gives"3". - mode
"w"gives"5". - mode
"c"gives"22". - mode
"all"gives"3\t5\t22".
With lines = ["hello", "world"], mode "all" gives "2\t2\t10". With an empty vector, mode "l" gives "0".
