Blogs Hub

Number of Segments in a String - MiniTV

Number of Segments in a String - मिनी टीवी

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Please note that the string does not contain any non-printable characters.

 

Example:

Input: "Hello, my name is John"

Output: 5

 

Solution:

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

namespace LeetCode.AskGif.Easy.String
{
    public class CountSegmentsSoln
    {
        public int CountSegments(string s)
        {
            if (s.Length == 0) return 0;
            var list = new List<string>();
            int count = 1;
            if(s[0] == ' ')
            {
                count = 0;
            }

            for(int i = 1; i < s.Length-1; i++)
            {
                if(s[i] == ' ' && s[i+1] != ' ')
                {
                    list.Add(s.Substring(0, i));
                    count++;
                }
            }

            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 CountSegmentsSolnTests
    {
        [TestMethod]
        public void CountSegmentsSoln_First()
        {
            var s = "Hello, my name is John";
            var output = 5;
            var res = new CountSegmentsSoln().CountSegments(s);

            Assert.AreEqual(res, output);
        }

        [TestMethod]
        public void CountSegmentsSoln_Second()
        {
            var s = "                ";
            var output = 0;
            var res = new CountSegmentsSoln().CountSegments(s);

            Assert.AreEqual(res, output);
        }

        [TestMethod]
        public void CountSegmentsSoln_Third()
        {
            var s = "Of all the gin joints in all the towns in all the world,   ";
            var output = 13;
            var res = new CountSegmentsSoln().CountSegments(s);

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