Number of Segments in a String
💻 coding

Number of Segments in a String

1 min read 222 words
1 min read
ShareWhatsAppPost on X
  • 1A segment in a string is defined as a contiguous sequence of non-space characters.
  • 2The provided solution counts segments in O(n) time complexity and O(1) space complexity.
  • 3Unit tests validate the functionality of the CountSegments method with various input strings.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"A segment in a string is defined as a contiguous sequence of non-space characters."

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

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 31 May 2020 · 1 min read · 222 words

Part of AskGif Blog · coding

You might also like