Length of Last Word - String - Easy - LeetCode
💻 coding

Length of Last Word - String - Easy - LeetCode

1 min read 186 words
1 min read
ShareWhatsAppPost on X
  • 1The problem requires returning the length of the last word in a given string, defined as a maximal substring of non-space characters.
  • 2If the last word does not exist, the function should return 0.
  • 3The provided solution has a time complexity of O(n) and a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem requires returning the length of the last word in a given string, defined as a maximal substring of non-space characters."

Length of Last Word - String - Easy - LeetCode

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.

Example:

Input: "Hello World"

Output: 5

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.String
{
 public class LengthOfLastWordSoln
 {
 public int LengthOfLastWord(string s)
 {
 int count = 0;
 int lastRes = 0;
 for (int i = 0; i < s.Length; i++)
 {
 if(s[i]==' ')
 {
 if(count != 0)
 {
 lastRes = count;
 }
 
 count = 0;
 }
 else
 {
 count++;
 }
 }
 if(count == 0)
 {
 count = lastRes;
 }

 return count;
 }
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Unit Tests:

using LeetCode.AskGif.Easy.String;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;

namespace CodingUnitTest.Easy.String
{
 [TestClass]
 public class LengthOfLastWordSolnTests
 {
 [TestMethod]
 public void LengthOfLastWordSoln_First()
 {
 var a = "Hello World"; 
 var output = 5;
 var res = new LengthOfLastWordSoln().LengthOfLastWord(a);

 Assert.AreEqual(res, output);
 }
 }
}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 4 June 2020 · 1 min read · 186 words

Part of AskGif Blog · coding

You might also like