Skip to content

Commit 3a42d15

Browse files
committed
Added Number of Segments in a String
1 parent 3a05ad6 commit 3a42d15

File tree

2 files changed

+67
-1
lines changed

2 files changed

+67
-1
lines changed

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,7 @@ pub mod longest_repeating_character_replacement; // 424 ✓
394394
// pub mod n_ary_tree_level_order_traversal; // 429 - This problem is unavailable in Rust
395395

396396
pub mod minimum_genetic_mutation; // 433 ✓
397-
397+
pub mod number_of_segments_in_a_string; // 434 ✓
398398
pub mod non_overlapping_intervals; // 435 ✓
399399

400400
pub mod path_sum_iii; // 437 ✓

src/number_of_segments_in_a_string.rs

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/// Given a string `s`, return the number of segments in the string.
2+
///
3+
/// A segment is defined to be a contiguous sequence of non-space characters.
4+
struct Solution;
5+
6+
impl Solution {
7+
8+
pub fn count_segments(s: String) -> i32 {
9+
let mut result = 0;
10+
let mut last_was_space = true;
11+
12+
for c in s.chars() {
13+
match c {
14+
' ' => {
15+
if !last_was_space {
16+
result += 1;
17+
last_was_space = true;
18+
}
19+
}
20+
_ => {
21+
last_was_space = false;
22+
}
23+
}
24+
}
25+
if !last_was_space {
26+
result += 1;
27+
}
28+
29+
result
30+
}
31+
32+
}
33+
34+
#[cfg(test)]
35+
mod tests {
36+
use super::Solution;
37+
38+
#[test]
39+
fn example_1() {
40+
let s = str!("Hello, my name is John");
41+
let result = Solution::count_segments(s);
42+
assert_eq!(result, 5);
43+
}
44+
45+
#[test]
46+
fn example_2() {
47+
let s = str!("Hello");
48+
let result = Solution::count_segments(s);
49+
assert_eq!(result, 1);
50+
}
51+
52+
#[test]
53+
fn example_3() {
54+
let s = str!("");
55+
let result = Solution::count_segments(s);
56+
assert_eq!(result, 0);
57+
}
58+
59+
#[test]
60+
fn example_4() {
61+
let s = str!(" ");
62+
let result = Solution::count_segments(s);
63+
assert_eq!(result, 0);
64+
}
65+
66+
}

0 commit comments

Comments
 (0)