Problem overview
The method countWords takes a List<String> of lines and returns the total number of words in all of them. This is a small version of the Unix wc -w command. A word is a run of characters separated from the next one by one or more spaces or tabs. Leading and trailing whitespace is ignored, and the input is plain ASCII.
For lines = ["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. A line made only of whitespace also counts 0, and an empty list gives 0.
Approach: trim, skip blanks, split
Handle one line at a time and add its word count to a running total. To count the words of a single line, cut it at every run of whitespace and count the pieces. Java's String.split does the cutting, but it has two habits that give wrong counts on messy input, so the line is cleaned up first.
These results come from real calls:
"".split("\\s+").lengthis 1. Splitting an empty string gives an array holding one empty string, which would count as a word." ".split("\\s+").lengthis 0. A whitespace-only string is cut into nothing but empty pieces, and Java drops trailing empty pieces." a b".split("\\s+")is["", "a", "b"], length 3. Leading whitespace produces an empty first piece, and that one is kept.
Trimming the line removes the leading and trailing whitespace, so no empty piece can appear at either end. After that, the only remaining problem is the empty line, which is skipped explicitly. Every piece of a trimmed, non-empty line is a real word.
Step by step
- Create
total. Anintstarting at 0 holds the sum, so an empty list returns 0 without any special case. - Loop over the lines with a for-each loop. The loop gives each entry as a
Stringnamedline, and no index is needed. - Trim the line into
trimmedwithline.trim(). Strings are immutable, sotrim()returns a new string and leaveslineunchanged. - Skip blank lines. If
trimmed.isEmpty(),continuejumps to the next line before any splitting happens. This covers both empty lines and whitespace-only lines, since the latter become empty after trimming. - Add the word count.
trimmed.split("\\s+")cuts the text at every run of whitespace, and.lengthis the number of pieces. Arrays uselengthwithout parentheses, unlike a string'slength(). - Return
totalafter the loop, so it runs once, when every line has been counted.
The solution in Java
class Solution {
public int countWords(List<String> lines) {
int total = 0;
for (String line : lines) {
String trimmed = line.trim();
if (trimmed.isEmpty()) continue;
total += trimmed.split("\\s+").length;
}
return total;
}
}
The Java details worth a closer look:
- The doubled backslash. The regular expression is
\s+:\smatches one whitespace character and+means one or more. A backslash starts an escape sequence inside a Java string literal, so it is written twice:"\\s+". splittakes a regular expression."a b".split(" ")has two spaces between the letters and returns three pieces, because every single space is a separator."a b".split("\\s+")returns two, because the whole run is one separator.- Tabs count too.
\smatches tabs as well as spaces, so" padded words\there "contains 3 words. Listneeds an import. In a standalone file the class needsimport java.util.List;(orjava.util.*).
Complexity
Time: O(n), where n is the total number of characters in all lines. Trimming and splitting each line read it a constant number of times.
Space: O(m), where m is the length of the longest line. trim() and split create a new string and an array of pieces for one line at a time, and these are garbage once the loop moves on.
Edge cases and common mistakes
- Skipping the trim. A line such as
" a b"would count as 3 words instead of 2, because of the empty first piece. - Skipping the empty check. With only the trim, an empty line would add 1, since splitting
""returns one piece. Whitespace-only lines are fine either way, but the empty line is not. - Splitting on
" ". Two spaces in a row, or a tab, give wrong counts. Use"\\s+". - An empty list. The loop runs zero times and the method returns 0.
- Counting lines instead of words.
lines.size()is the number of lines. Words need the inner count.
Testing
["hello world", "foo bar baz", ""]gives5.[" padded words\there "]gives3.[" ", "\t"]gives0.[]gives0.
