Problem overview
The method countChars takes a List<String> of lines and returns the total number of characters across all of them. This is a simplified version of the character count in the Unix wc command, with one convention: only the characters inside each line count, not the newlines that separate lines. The answer is simply the sum of the line lengths. Spaces and tabs inside a line count as one character each.
For ["hello", "world"] the answer is 10, since each word has 5 characters. An empty line adds 0, and an empty list gives 0.
Approach: one running total
There is nothing to cut apart or compare here. Visit every line, ask it for its length, and add that to a total. The version before this one needed a split to find words, but characters are already available through length().
Step by step
- Create
total, anintthat starts at 0. A sum always starts at zero, before any line has been added, and that is also the right answer for an empty list. - Loop over the lines with a for-each loop, taking each entry as the
Stringline. - Add the line's length.
line.length()is the number of characters in that one string, sototal += line.length()grows the sum by exactly that much. - Return
totalafter the loop, so the return happens once, when every line has been counted.
The solution in Java
class Solution {
public int countChars(List<String> lines) {
int total = 0;
for (String line : lines) {
total += line.length();
}
return total;
}
}
A few Java details:
- Strings use
length(), arrays uselength. AStringhas a method, so it needs the parentheses. Writingline.lengthwithout them does not compile. - What
length()counts. It counts UTF-16 code units. For plain ASCII text, which is all this lesson uses, that is the same as the number of characters. A single emoji such as"\uD83D\uDE00"has a length of 2, so for text outside ASCII the result would differ from what a person would count. - The
inttotal. It can hold values up to about 2.1 billion. Test inputs are far smaller, but a total over that limit would wrap around silently. Listneeds an import. In a standalone file, addimport java.util.List;.
Edge cases and common mistakes
- Empty lines and an empty list.
["", ""]and[]both return 0. The first loop adds two zeros, the second does not run at all. - Whitespace counts.
["a b\tc", ""]returns 5: three letters, one space and one tab. Do not trim the line, because trimming would remove characters that the count is supposed to include.[" "]returns 2. - Counting newlines. Adding 1 per line for a separator is what the real command does, but not what this lesson asks for.
- Returning inside the loop. A
returnplaced before the closing brace of the loop would stop after the first line.
Testing
["hello", "world"]gives10.["a b\tc", ""]gives5.[" "]gives2.["", ""]gives0.[]gives0.
