Count the number of words in a string, where a word is a contiguous sequence of non-space characters.
Note that you may assume the string does not contain any non-printable characters.
Example:
Input: "Hello, my name is John" Output: 5 Explanation: A word is a contiguous sequence of non-space characters, so "Hello," counts as one word.
Analysis#
This problem is somewhat like a state machine. We need to maintain whether the previous character was part of a word. If the previous character is a space and the next one is not, a new word has started.
Rust Code#
# struct Solution;
impl Solution {
pub fn count_segments(s: String) -> i32 {
let mut state = 0;
let mut res = 0;
for ch in s.chars() {
if ch == ' ' {
state = 0;
} else {
if state == 0 {
res += 1;
}
state = 1;
}
}
res
}
}
