Skip to content

Commit e7cd083

Browse files
committed
zigzag pattern
1 parent 69cb8e4 commit e7cd083

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@ pub mod add_two_numbers;
55
pub mod length_of_longest_substring;
66
pub mod find_median_sorted_arrays;
77
pub mod longest_palindrome;
8+
pub mod zigzag_conversion;

src/zigzag_conversion.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
}

0 commit comments

Comments
 (0)