Today I was practicing some C# by solving some Leet Code problems. I came across one that was fairly easy, but I wanted to write about it because there are numerous ways to go about solving it. One of the easiest ways to solve it is by using LINQ. LINQ stands for Language Integrated Query and it allows you to write C# statements in a SQL-like way to select specific data from data sets. I use LINQ quite often when working with data sets in C# because it saves you a lot of time writing code. Whether you are creating a web app or just a console application, LINQ is the go-to way to quickly filter data down in a quick and easy way. Here is the documentation on LINQ from Microsoft.
In this post I will be solving the Leet Code problem in a way that most everyone can understand. After that, I will solve it with LINQ… in one line.
The Problem
The Leet Code problem (problem #58) is pretty simple but without LINQ it would take a few lines of code to solve. The problem goes like this:
Given a string s consisting of words and spaces, return the length of the last word in the string.
Pretty straight forward. Here are the three example strings that we will be analyzing:
Input: s = “Hello World”;
Input: s = “ fly me to the moon “;
Input: s = “luffy is still joyboy”
When you run these through your code you should expect the integer output of: 5
, 4
, 6
.
Regular Solution
Like I had mentioned, there are a lot of ways that someone can solve this issue. I put together a short solution that is easy to understand. I wrote this in a .NET 6 Console Application. Here is the code:
# region Test Variables
string s = "Hello World"; // Result: 5
//string s = " fly me to the moon "; // Result: 4
//string s = "luffy is still joyboy"; // Result: 6
# endregion
# region Regular Solution
// Split on a space (' ') to create a word array
string[] stringArrayTemp = s.Split(' ');
// Use a list to store non whitespace elements while going
// through array
List<string> nonWhitespaceElements = new List<string>();
// Remove blank or whitespace elements in the array
foreach (string str in stringArrayTemp)
{
if (!string.IsNullOrWhiteSpace(str))
{
// No whitespace or null; add to list
nonWhitespaceElements.Add(str);
}
}
// Get the last word in the list
string lastWordInArray = nonWhitespaceElements[nonWhitespaceElements.Count - 1];
// Get the length of the word and print it to the console
Console.WriteLine(lastWordInArray.Length);
# endregion
As you can see, in the beginning portion I have a region holding the three test inputs. I just comment and uncomment to try each one against the code. In the next section, I have the main section of code. In the first part I split the string into an array by splitting it up based on spaces. The first example (“Hello World”
), would result in a two element array because there is one space (‘ ’
). The first element is “Hello”
and the second is “World”
.
In the next line, I create a list that will contain strings that are not empty elements. The reason being splitting and having two consecutive spaces will result in an empty element. The second input is an example of this. After this, I run through each element and if it is not null or empty, I will add it to the list.
Finally, I get the last word in the list by using the length of the list (minus one) as the index selector of the list and print the length of the last word (Length is an integer).
From this example, we can run each input and get the desired result. This works very well and it is easy to read and understand. When I run this code in the Leet Code solution processor, it passes but it is sort of slow. We will fix that with LINQ.
LINQ Solution
Here is the LINQ solution. It might look a little funky but don’t worry, we will break it down.
# region Test Variables
string s = "Hello World"; // Result: 5
//string s = " fly me to the moon "; // Result: 4
//string s = "luffy is still joyboy"; // Result: 6
# endregion
# region LINQ Solution
Console.WriteLine(s.Split(' ').Where(x => !string.IsNullOrWhiteSpace(x)).Last().Length);
# endregion
One line. All of that other code but in one line. Pretty awesome right?
In the first part, we are printing the final result’s length. Inside of the Console.WriteLine()
set of parentheses, we start with the same as before split. Instead of just dumping the entire set of elements into an array like we did before, we are now going to also filter it with the Where()
extension. Inside of the Where()
, we state that the elements we want cannot be null or just be whitespace with x => !string.IsNullOrWhiteSpace(x)
, with x
being the current element in the filter iteration. Once the filter is passed, we then select the last element in the filtered dataset with the Last()
extension. Now that we are down to the last element, we can now get the length.
With this example, we can see the same process but in a smaller, simpler form. If you run this through the Leet Code solution processor, it also passes but is a lot faster than the previous code.