File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -58,3 +58,4 @@ mod n0054_spiral_matrix;
5858mod n0055_jump_game;
5959mod n0056_merge_intervals;
6060mod n0057_insert_interval;
61+ mod n0058_length_of_last_word;
Original file line number Diff line number Diff line change 1+ /**
2+ * [58] Length of Last Word
3+ *
4+ * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
5+ *
6+ * If the last word does not exist, return 0.
7+ *
8+ * Note: A word is defined as a character sequence consists of non-space characters only.
9+ *
10+ * Example:
11+ *
12+ * Input: "Hello World"
13+ * Output: 5
14+ *
15+ *
16+ */
17+ pub struct Solution { }
18+
19+ // submission codes start here
20+
21+ impl Solution {
22+ pub fn length_of_last_word ( s : String ) -> i32 {
23+ let seq: Vec < char > = s. chars ( ) . rev ( ) . collect ( ) ;
24+ let mut result = 0 ;
25+ let mut find = false ;
26+ for ch in seq {
27+ if ch == ' ' && find {
28+ break ;
29+ }
30+ if ch != ' ' {
31+ find = true ;
32+ result += 1 ;
33+ }
34+ }
35+ result
36+ }
37+ }
38+
39+ // submission codes end
40+
41+ #[ cfg( test) ]
42+ mod tests {
43+ use super :: * ;
44+
45+ #[ test]
46+ fn test_58 ( ) {
47+ assert_eq ! ( Solution :: length_of_last_word( "Hello World" . to_owned( ) ) , 5 ) ;
48+ assert_eq ! ( Solution :: length_of_last_word( " " . to_owned( ) ) , 0 ) ;
49+ assert_eq ! ( Solution :: length_of_last_word( "" . to_owned( ) ) , 0 ) ;
50+ assert_eq ! ( Solution :: length_of_last_word( " rrrrr " . to_owned( ) ) , 5 ) ;
51+ }
52+ }
You can’t perform that action at this time.
0 commit comments