Problem overview
The -w flag of wc counts words. The function countWords takes a vector<string> of lines and returns the total number of words across all of them as an int. A word is a run of characters without whitespace, and words are separated by one or more spaces or tabs. Leading and trailing whitespace is ignored, a line with no words (empty, or only whitespace) adds 0, and an empty vector gives 0.
For ["hello world", "foo bar baz", ""] the answer is 5: the first line has 2 words, the second has 3 and the empty line has none.
Approach: let a string stream split the line
Counting words by hand means tracking whether you are inside a word or between words, with special cases for leading spaces, trailing spaces and runs of several spaces. C++ already has a tool that does this work. An istringstream is an input stream whose text comes from a string instead of the keyboard. Reading from it with >> into a string skips any whitespace in front and then collects characters up to the next whitespace. That is exactly one word.
The expression ss >> word also gives back the stream itself, and a stream used as a condition is true only while the last read succeeded. When the line has no more words, the read fails and the condition becomes false. So while (ss >> word) runs once per word, and counting inside it counts the words. A blank line, or a line of only spaces and tabs, fails on the first read and adds nothing.
Tabs need no extra code: the stream treats every whitespace character the same way, so "a\tb" holds two words just like "a b" does.
Step by step
- Create
totalas anintset to 0. It accumulates the words of all lines, so it must start at zero before any line is read. - Loop over the lines by position with
ifrom 0 whilei < lines.size(). - Make an
istringstreamnamedssfromlines[i]. A fresh stream per line keeps the lines separate: each one is read from its start. - Create an empty
stringnamedword. Every successful read stores its word here. The text itself is never used; the variable only gives the read somewhere to put it. - Write
while (ss >> word). The loop ends when the line has no words left. - Add 1 to
totalinside that loop. The body runs once for each word. - Return
totalafter the outer loop. The return sits outside both loops, so it runs once after every line has been counted.
The solution in C++
class Solution {
public:
int countWords(vector<string> lines) {
int total = 0;
for (int i = 0; i < lines.size(); i++) {
istringstream ss(lines[i]);
string word;
while (ss >> word) {
total++;
}
}
return total;
}
};
The C++ details worth a closer look:
- The header.
istringstreamcomes from<sstream>. In the lesson it is already included at the top of the file; in a program of your own you add#include <sstream>. - Reading into a
stringstops at whitespace. That is why>>gives words and not whole lines. To read a whole line you would usegetline, which is a different tool. - The stream in a condition. The loop test is the read itself. Writing a separate check such as
while (!ss.eof())is a common mistake: the end-of-file flag is only set after a read has already failed, so such a loop runs one extra time and counts a word that isn't there. - The signed and unsigned comparison.
lines.size()is an unsigned type andiis anint. The comparison works for any realistic number of lines, and some compilers warn about it. - The vector is passed by value. The signature is fixed by the lesson, so the call copies the vector. A
const vector<string>¶meter would avoid the copy, and you will see it often in larger programs.
Complexity
Time: O(total length). Each line is copied into a stream once and read once from left to right, so the work is proportional to the number of characters, summed over all lines.
Space: O(total length) in this version. Beyond the copy of the input made by the by-value parameter, the extra memory is the stream for one line and the word string, which together are proportional to the longest line.
Edge cases and common mistakes
- Empty vector. The loop never runs and the function returns 0.
- Empty and blank lines.
[" a \t b ", " "]gives 2: the first line has two words surrounded by extra whitespace, and the second line is only spaces. - Counting spaces instead of words. Counting the separators and adding 1 per line gives wrong answers for empty lines, doubled spaces and leading or trailing whitespace. The stream handles all of these without special cases.
- Tabs.
["a\tb\tc"]gives 3. A tab separates words just as a space does. - Reusing one stream for every line. After a stream has failed a read, it stays in the failed state. Creating
ssinside the loop gives each line a clean stream. - Counting lines. Adding 1 to
totalonce per line instead of once per word gives the number of lines, not words.
Testing
["hello world", "foo bar baz", ""]gives5.[" a \t b ", " "]gives2.["a\tb\tc"]gives3.[]gives0.
