Skip to content

Commit 57b93bc

Browse files
committed
resolve aylei#6
1 parent 4a0c359 commit 57b93bc

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ mod n0002_add_two_numbers;
33
mod n0003_longest_substring;
44
mod n0004_median_of_two_sorted_arrays;
55
mod n0005_longest_palindromic_substring;
6+
mod n0006_zigzag_conversion;

src/n0006_zigzag_conversion.rs

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/**
2+
* [6] ZigZag Conversion
3+
*
4+
* The string <code>"PAYPALISHIRING"</code> is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
5+
*
6+
*
7+
* P A H N
8+
* A P L S I I G
9+
* Y I R
10+
*
11+
*
12+
* And then read line by line: <code>"PAHNAPLSIIGYIR"</code>
13+
*
14+
* Write the code that will take a string and make this conversion given a number of rows:
15+
*
16+
*
17+
* string convert(string s, int numRows);
18+
*
19+
* Example 1:
20+
*
21+
*
22+
* Input: s = "PAYPALISHIRING", numRows = 3
23+
* Output: "PAHNAPLSIIGYIR"
24+
*
25+
*
26+
* Example 2:
27+
*
28+
*
29+
* Input: s = "PAYPALISHIRING", numRows = 4
30+
* Output: "PINALSIGYAHRPI"
31+
* Explanation:
32+
*
33+
* P I N
34+
* A L S I G
35+
* Y A H R
36+
* P I
37+
*
38+
*/
39+
pub struct Solution {}
40+
41+
// submission codes start here
42+
43+
impl Solution {
44+
pub fn convert(s: String, num_rows: i32) -> String {
45+
if num_rows < 2 {
46+
return s;
47+
}
48+
let seq: Vec<char> = s.chars().collect();
49+
let len = seq.len();
50+
let unit: usize = (2 * num_rows - 2) as usize;
51+
let mut sb = String::with_capacity(s.capacity());
52+
for row in 0..num_rows {
53+
let mut i = row as usize;
54+
let step1 = 2 * (num_rows - 1 - row) as usize;
55+
let step2 = (unit - step1) as usize;
56+
let mut trigger = false;
57+
while i < len {
58+
sb.push(seq[i]);
59+
if step1 == 0 {
60+
i += step2
61+
} else if step2 == 0 {
62+
i += step1
63+
} else {
64+
i += if trigger { step2 } else { step1 };
65+
trigger = !trigger;
66+
}
67+
}
68+
}
69+
sb
70+
}
71+
}
72+
73+
// submission codes end
74+
75+
#[cfg(test)]
76+
mod tests {
77+
use super::*;
78+
79+
#[test]
80+
fn test_6() {
81+
assert_eq!(Solution::convert("PAYPALISHIRING".to_string(), 4), "PINALSIGYAHRPI");
82+
assert_eq!(Solution::convert("PAYPALISHIRING".to_string(), 3), "PAHNAPLSIIGYIR");
83+
assert_eq!(Solution::convert("A".to_string(), 1), "A");
84+
assert_eq!(Solution::convert("AY".to_string(), 2), "AY");
85+
}
86+
}

0 commit comments

Comments
 (0)