arcbjorn

thoughtbook

RSS Feed

Wednesday, December 28, 2022

Number of segments in a string

Leetcode 434 problem.

A function, given a string s, to return the number of segments in the string. A segment is defined to be a contiguous sequence of non-space characters.

Go

  • Time complexity: O(nlogn)O(n * log_{n}) - n is a length of a string
  • Auxiliary space: O(n)O(n) - n is a length of a string
func countSegments(s string) int {
    trimmedS := strings.Trim(s, " ")
    length := len(trimmedS)

    if length == 0 {
        return 0
    }

    var segmentsNumber int

    for idx, rune := range trimmedS {
        // skip last character
        if (idx+1 == length) {
            continue
        }

        nextRune := trimmedS[idx+1]
        // count only if next character is not whitespace
        if string(rune) == " " && string(nextRune) != " " {
            segmentsNumber++
        }
    }

    return segmentsNumber+1
}
Creative Commons Licence