File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -5,3 +5,4 @@ pub mod add_two_numbers;
55pub mod length_of_longest_substring;
66pub mod find_median_sorted_arrays;
77pub mod longest_palindrome;
8+ pub mod zigzag_conversion;
Original file line number Diff line number Diff line change 1+ // What's zigzag pattern?
2+ // https://discuss.leetcode.com/topic/22925/if-you-are-confused-with-zigzag-pattern-come-and-see
3+ pub fn zigzag_conversion ( string : & str , num : usize ) -> String {
4+ if num <= 1 { return string. to_string ( ) } ;
5+ let mut res: Vec < Vec < char > > = Vec :: with_capacity ( num) ;
6+ for _ in 0 ..num {
7+ res. push ( Vec :: with_capacity ( string. chars ( ) . count ( ) / num + 1 ) )
8+ }
9+ let chars = string. chars ( ) . into_iter ( ) ;
10+ let mut index: usize = 0 ;
11+ let mut increase: bool = true ;
12+ for c in chars {
13+ res[ index] . push ( c) ;
14+ if increase {
15+ index += 1 ;
16+ } else {
17+ index -= 1 ;
18+ }
19+ if index % ( num - 1 ) == 0 { increase = !increase; }
20+ }
21+
22+ return res. into_iter ( ) . map ( |i| i. into_iter ( ) . collect :: < String > ( ) ) . collect :: < String > ( ) ;
23+ }
24+
25+ #[ cfg( test) ]
26+ mod test {
27+ use super :: zigzag_conversion;
28+
29+ #[ test]
30+ fn test_zigzag_conversion ( ) {
31+ assert_eq ! ( zigzag_conversion( "PAYPALISHIRING" , 3 ) , "PAHNAPLSIIGYIR" ) ;
32+
33+ assert_eq ! ( zigzag_conversion( "PAYPALISHIRING" , 1 ) , "PAYPALISHIRING" ) ;
34+
35+ assert_eq ! ( zigzag_conversion( "我叫金三顺" , 3 ) , "我顺叫三金" ) ;
36+ }
37+ }
You can’t perform that action at this time.
0 commit comments