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

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

All Problems

All Solutions