File tree Expand file tree Collapse file tree 2 files changed +67
-1
lines changed Expand file tree Collapse file tree 2 files changed +67
-1
lines changed Original file line number Diff line number Diff line change @@ -394,7 +394,7 @@ pub mod longest_repeating_character_replacement; // 424 ✓
394
394
// pub mod n_ary_tree_level_order_traversal; // 429 - This problem is unavailable in Rust
395
395
396
396
pub mod minimum_genetic_mutation; // 433 ✓
397
-
397
+ pub mod number_of_segments_in_a_string ; // 434 ✓
398
398
pub mod non_overlapping_intervals; // 435 ✓
399
399
400
400
pub mod path_sum_iii; // 437 ✓
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments