Skip to main content
Back to problems
#434
Easy Algorithms

Number of segments in a string

String
37.0% acceptance
Jan 13, 2026
903
1335
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.

Solution

Rust
Time O(1)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_segments(s: String) -> i32 {
    s.split_whitespace().count() as i32
  }
}