Problem overview
Wc combines the three earlier counts. It takes a list of lines and a mode string and returns a string:
"l": the number of lines."w": the number of whitespace-separated words."c": the total of the line lengths, with no newlines.- anything else,
"all"included: lines, words and characters joined by tab characters.
For ["hello", "world"] and mode "all" the result is "2\t2\t10". Modes are case-sensitive, so "L" falls into the "anything else" case. For an empty list, "l", "w" and "c" return "0" and "all" returns "0\t0\t0".
Approach
Compute all three numbers once, then pick what to return. The line count needs no loop: it is the size of the list. The word and character counts both grow as the loop reads lines, so one pass collects both. After the loop, a few early returns handle the three single-count modes, and the last line, reached by every other mode, builds the combined string.
The counts are numbers but the method returns text, so each one must be converted to a string before it is returned.
The combined output is deliberately simple. The real wc pads its columns with spaces and lets you combine flags, but here the three numbers are joined by single tab characters, so a test can compare the whole string exactly. Check the order when you write the last line: lines first, then words, then characters, the same order as the mode names in the list above.
A worked example
Take ["a b", " "] with mode "L". numLines is 2. The first line trims to "a b", which has 2 words, and adds 3 characters. The second line trims to the empty string, so no words are added, but its 2 spaces still count as characters. The totals are 2 lines, 2 words and 5 characters. No mode check matches "L", so the combined string "2\t2\t5" is returned.
Step by step
- Store
numLinesas the list'sCount. - Create
numWordsandnumChars, bothints starting at 0. - Loop over the lines with
foreach. - Trim the line into
trimmedwithTrim(), which removes whitespace at both ends. - Count words only for a non-blank line. If
trimmed.Lengthis above 0, add the number of pieces from splitting it on whitespace, with empty pieces removed. - Add the full line's
LengthtonumChars. This usesline, nottrimmed, because the spaces at the edges are characters too. - Return early for
"l","w"and"c", converting the matching number withToString(). - Return the combined string last, for every mode that did not return above.
The solution in C#
class Solution {
public string Wc(List<string> lines, string mode) {
int numLines = lines.Count;
int numWords = 0;
int numChars = 0;
foreach (string line in lines) {
string trimmed = line.Trim();
if (trimmed.Length > 0) { numWords += trimmed.Split((char[])null, StringSplitOptions.RemoveEmptyEntries).Length; }
numChars += line.Length;
}
if (mode == "l") { return numLines.ToString(); }
if (mode == "w") { return numWords.ToString(); }
if (mode == "c") { return numChars.ToString(); }
return numLines + "\t" + numWords + "\t" + numChars;
}
}
The details worth knowing:
==on strings compares contents.mode == "l"is true for any string with the textl, not only the same object. It is case-sensitive, so"L"does not match.- Splitting on
nullseparators cuts at any whitespace, andRemoveEmptyEntriesdrops the empty pieces. TheTrimcheck keeps blank lines from being split at all, though they would give 0 pieces anyway. +turns numbers into text. In the last line, anintadded to a string is converted and appended, so the whole expression is one string. The tab is the escape"\t", a single character.- Early returns replace
else. Once a branch returns, the code after it only runs for the other modes, so noelseis needed. - The default is "all". A mode such as
"x"skips the three checks and gets the combined string.
Why one pass
You could write three small methods, one for each count, and call the right one for the mode. That works, but it reads the lines again for each count, and the combined mode would run all three. Computing the three numbers together in one loop keeps the method short and reads the input once. The cost is that the single-count modes also compute numbers they do not return, which is cheap here.
Complexity
Time: O(total characters), since trimming and splitting each line reads it. Space: the split of one line creates an array of its words, so extra memory is proportional to the longest line.
Edge cases and common mistakes
- Measuring characters on the trimmed line. That loses the edge spaces.
" a "has 4 characters and 1 word. - Returning a number.
return numLines;does not compile in a method that returnsstring. - Treating
"L"or"x"as an error. They get the combined result. - An empty list.
numLinesis 0 and the loop does nothing, so every count is 0.
Testing
["hello", "world"]with"all"gives"2\t2\t10".["a b", " "]with"L"gives"2\t2\t5".["a\tb"]with"c"gives"3".[]with"all"gives"0\t0\t0".
