Welcome to Subscribe On Youtube

434. Number of Segments in a String

Description

Given a string s, return the number of segments in the string.

A segment is defined to be a contiguous sequence of non-space characters.

 

Example 1:

Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]

Example 2:

Input: s = "Hello"
Output: 1

 

Constraints:

  • 0 <= s.length <= 300
  • s consists of lowercase and uppercase English letters, digits, or one of the following characters "!@#$%^&*()_+-=',.:".
  • The only space character in s is ' '.

Solutions

Solution 1: String Splitting

We split the string $\textit{s}$ by spaces and then count the number of non-empty words.

The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $\textit{s}$.

Solution 2: Simulation

We can also directly traverse each character $\text{s[i]}$ in the string. If $\text{s[i]}$ is not a space and $\text{s[i-1]}$ is a space or $i = 0$, then $\text{s[i]}$ marks the beginning of a new word, and we increment the answer by one.

After the traversal, we return the answer.

The time complexity is $O(n)$, where $n$ is the length of the string $\textit{s}$. The space complexity is $O(1)$.

  • class Solution {
        public int countSegments(String s) {
            int ans = 0;
            for (int i = 0; i < s.length(); ++i) {
                if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) {
                    ++ans;
                }
            }
            return ans;
        }
    }
    
    
    // Solution 2
    class Solution {
        public int countSegments(String s) {
            int ans = 0;
            for (int i = 0; i < s.length(); ++i) {
                if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) {
                    ++ans;
                }
            }
            return ans;
        }
    }
    
    
  • class Solution {
    public:
        int countSegments(string s) {
            int ans = 0;
            for (int i = 0; i < s.size(); ++i) {
                if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) {
                    ++ans;
                }
            }
            return ans;
        }
    };
    
    
    // Solution 2
    class Solution {
    public:
        int countSegments(string s) {
            int ans = 0;
            for (int i = 0; i < s.size(); ++i) {
                if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) {
                    ++ans;
                }
            }
            return ans;
        }
    };
    
    
  • class Solution:
        def countSegments(self, s: str) -> int:
            ans = 0
            for i, c in enumerate(s):
                if c != ' ' and (i == 0 or s[i - 1] == ' '):
                    ans += 1
            return ans
    
    
    # Solution 2
    class Solution:
        def countSegments(self, s: str) -> int:
            ans = 0
            for i, c in enumerate(s):
                if c != ' ' and (i == 0 or s[i - 1] == ' '):
                    ans += 1
            return ans
    
    
  • func countSegments(s string) int {
    	ans := 0
    	for i, c := range s {
    		if c != ' ' && (i == 0 || s[i-1] == ' ') {
    			ans++
    		}
    	}
    	return ans
    }
    
    
    // Solution 2
    func countSegments(s string) int {
    	ans := 0
    	for i, c := range s {
    		if c != ' ' && (i == 0 || s[i-1] == ' ') {
    			ans++
    		}
    	}
    	return ans
    }
    
    
  • class Solution {
        /**
         * @param String $s
         * @return Integer
         */
        function countSegments($s) {
            $arr = explode(' ', $s);
            $cnt = 0;
            for ($i = 0; $i < count($arr); $i++) {
                if (strlen($arr[$i]) != 0) {
                    $cnt++;
                }
            }
            return $cnt;
        }
    }
    
    
    // Solution 2
    class Solution {
        /**
         * @param String $s
         * @return Integer
         */
        function countSegments($s) {
            $ans = 0;
            $n = strlen($s);
            for ($i = 0; $i < $n; $i++) {
                $c = $s[$i];
                if ($c !== ' ' && ($i === 0 || $s[$i - 1] === ' ')) {
                    $ans++;
                }
            }
            return $ans;
        }
    }
    
    
  • function countSegments(s: string): number {
        return s.split(/\s+/).filter(Boolean).length;
    }
    
    
    // Solution 2
    function countSegments(s: string): number {
        let ans = 0;
        for (let i = 0; i < s.length; i++) {
            let c = s[i];
            if (c !== ' ' && (i === 0 || s[i - 1] === ' ')) {
                ans++;
            }
        }
        return ans;
    }
    
    

All Problems

All Solutions