Problem overview
The method wc combines the three earlier counters. It takes a List<String> of lines and a String mode, and returns a String:
"l"gives the number of lines;"w"gives the number of words, meaning whitespace-separated tokens;"c"gives the number of characters, the sum of the line lengths with no newlines counted;"all"gives the three numbers separated by tab characters: lines, words, characters.
Any other mode, such as "x" or "L" (modes are case-sensitive), behaves like "all". This interface is the lesson's own, not the real wc flags. For ["hello", "world"] with mode "all" the result is "2\t2\t10": 2 lines, 2 words and 10 characters.
Approach: count everything once, then choose
Computing the answer for one mode needs the same loop as for another, so the method counts all three numbers in a single pass and picks the one to return afterwards. The line count needs no loop at all: it is the size of the list. Words and characters are accumulated while the loop reads each line.
Returning the right thing is an if chain on mode. Each of the three known modes returns early, and the last line, which handles "all" and every unknown mode, is reached only when none of them matched. That is how unknown modes fall back to the full report without any extra code.
The cost of computing all three numbers even when only one is asked for is small: the loop is linear and the extra work per line is one trim, one split and one length. Writing three separate loops, one per mode, would repeat the same traversal code and make the modes easier to get out of step with each other, for example by trimming in one place and forgetting it in another. One pass with three counters keeps the definitions of a word and a character in a single place.
Step by step
- Store the line count in
numLineswithlines.size(). - Create
numWordsandnumCharsasints starting at 0. They grow as the loop reads lines. - Loop over the lines with a for-each loop, naming each entry
line. - Trim the line into
trimmed. Spaces at the two ends would produce empty pieces when splitting. - Add the words, if there are any. If
trimmedis not empty, addtrimmed.split("\\s+").lengthtonumWords. An empty string split this way returns one empty piece, so blank lines must be skipped. - Add the characters.
line.length()comes from the original line, nottrimmed, because spaces count as characters here. - Return the line count for
"l". The method returns text, soInteger.toString(numLines)converts theint. Compare the mode withequals, not==. - Return the word count for
"w"the same way. - Return the character count for
"c"the same way. - Return the combined text last, outside any branch, with the three numbers joined by
"\t".
The solution in Java
class Solution {
public String wc(List<String> lines, String mode) {
int numLines = lines.size();
int numWords = 0;
int numChars = 0;
for (String line : lines) {
String trimmed = line.trim();
if (!trimmed.isEmpty()) numWords += trimmed.split("\\s+").length;
numChars += line.length();
}
if (mode.equals("l")) return Integer.toString(numLines);
if (mode.equals("w")) return Integer.toString(numWords);
if (mode.equals("c")) return Integer.toString(numChars);
return numLines + "\t" + numWords + "\t" + numChars;
}
}
The Java details worth a closer look:
equalsagainst==. On objects,==compares references, not contents. A mode that arrives as a differentStringobject with the same text fails the==test: withString m1 = new String("l"),m1 == "l"isfalseandm1.equals("l")istrue. Callingwc(["a"], m1)returns"1"withequals, as it should.- Which side calls
equals.mode.equals("l")would throw aNullPointerExceptionifmodewerenull. The lesson never passesnull, but"l".equals(mode)is the habit that tolerates it. - Joining numbers and text with
+. InnumLines + "\t" + numWords + ...the first+has aninton the left and aStringon the right, so Java converts the number to text and concatenates. The order matters:1 + 2 + "\t"adds the numbers first and gives"3\t". Here a string appears right after the first number, so each number becomes text on its own. - The tab character.
"\t"is a single tab, one character, not a backslash and a letter.
Complexity
Time: O(n), where n is the total number of characters: one pass trims, splits and measures each line. The line count is O(1).
Space: O(m), where m is the longest line, for the trimmed copy and the pieces of one split at a time.
Edge cases and common mistakes
- An empty list.
"l","w"and"c"each return"0", and"all"returns"0\t0\t0". - Unknown modes.
"x"and"L"return the same text as"all","2\t2\t10"for the hello and world example. - Blank lines in the middle.
["one two", "", " three "]with"all"gives"3\t3\t16". The empty line counts as a line, adds no words and no characters, and the padding spaces aroundthreeare part of the character count. - Counting characters from
trimmed. That drops the surrounding spaces and gives too small a total. - Returning a number. The method's return type is
String.return numLines;does not compile. - A word count without the empty check. A blank line would add 1.
Testing
With lines = ["hello", "world"]:
- mode
"l"gives"2"; - mode
"w"gives"2"; - mode
"c"gives"10"; - mode
"all"gives"2\t2\t10".
Other inputs: [] with "all" gives "0\t0\t0", [] with "w" gives "0", and ["one two", "", " three "] with "all" gives "3\t3\t16".
