Blogs Hub

Length of Last Word - String - Easy - LeetCode - MiniTV

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);
        }
    }
}