File tree Expand file tree Collapse file tree 5 files changed +68
-0
lines changed
reverse_words_in_a_string_iii Expand file tree Collapse file tree 5 files changed +68
-0
lines changed Original file line number Diff line number Diff line change @@ -10,4 +10,5 @@ members = [
10
10
" merge_sorted_array" ,
11
11
" intersection_of_two_arrays" ,
12
12
" longest_palindromic_substring" ,
13
+ " reverse_words_in_a_string_iii" ,
13
14
]
Original file line number Diff line number Diff line change @@ -16,6 +16,7 @@ Resolving problems of LeetCode in RustLang.
16
16
* [ 215. Kth Largest Element in an Array] ( ./kth_largest/src/lib.rs )
17
17
* [ 232. Implement Queue using Stacks] ( ./implement_queue_using_stacks/src/lib.rs )
18
18
* [ 349. Intersection of Two Arrays] ( ./intersection_of_two_arrays/src/lib.rs )
19
+ * [ 557. Reverse Words in a String III] ( ./reverse_words_in_a_string_iii/src/lib.rs )
19
20
20
21
## Document
21
22
Original file line number Diff line number Diff line change
1
+ [package ]
2
+ name = " reverse_words_in_a_string_iii"
3
+ version = " 0.1.0"
4
+ authors = [" Ryan Li <conbas2019@gmail.com>" ]
5
+ edition = " 2018"
6
+
7
+ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8
+
9
+ [dependencies ]
Original file line number Diff line number Diff line change
1
+ /*!
2
+ * # 557. Reverse Words in a String III
3
+ *
4
+ * [Problem link](https://leetcode.com/problems/reverse-words-in-a-string-iii/)
5
+ */
6
+
7
+ #![ allow( dead_code) ]
8
+
9
+ struct Solution { }
10
+
11
+ // ----------------------------------------------------------------------------
12
+
13
+ impl Solution {
14
+ pub fn reverse_words ( s : String ) -> String {
15
+ let mut i = 0 ;
16
+ let chars = s. chars ( ) . collect :: < Vec < char > > ( ) ;
17
+ let mut reversed = vec ! [ ] ;
18
+ while i < s. len ( ) {
19
+ if chars[ i] == ' ' {
20
+ reversed. push ( chars[ i] ) ;
21
+ i += 1 ;
22
+ continue ;
23
+ }
24
+ let mut j = i;
25
+ while j < s. len ( ) && chars[ j] != ' ' {
26
+ j += 1 ;
27
+ }
28
+ let mut k = j - 1 ;
29
+ loop {
30
+ // push the char into the reversed vector until reach the index `i`
31
+ reversed. push ( chars[ k] ) ;
32
+ if k == i {
33
+ break ;
34
+ }
35
+ k -= 1 ;
36
+ }
37
+ i = j;
38
+ }
39
+ reversed. iter ( ) . collect ( )
40
+ }
41
+ }
42
+
43
+ #[ cfg( test) ]
44
+ mod tests {
45
+ use super :: * ;
46
+
47
+ #[ test]
48
+ fn test_example_1 ( ) {
49
+ let input = "Let's take LeetCode contest" . to_string ( ) ;
50
+ let output = "s'teL ekat edoCteeL tsetnoc" . to_string ( ) ;
51
+ assert_eq ! ( Solution :: reverse_words( input) , output) ;
52
+ }
53
+ }
You can’t perform that action at this time.
0 commit comments