Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 79eab9a

Browse files
committed
solve 6
1 parent ca46b66 commit 79eab9a

File tree

2 files changed

+104
-0
lines changed

2 files changed

+104
-0
lines changed

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ mod s0001_two_sum;
22
mod s0002_add_two_numbers;
33
mod s0003_longest_substring_without_repeating_characters;
44
mod s0005_longest_palindromic_substring;
5+
mod s0006_zigzag_conversion;
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
use std::rc::Rc;
2+
3+
/**
4+
* [6] N 字形变换
5+
*
6+
* 将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
7+
* 比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:
8+
*
9+
* P A H N
10+
* A P L S I I G
11+
* Y I R
12+
* 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。
13+
* 请你实现这个将字符串进行指定行数变换的函数:
14+
*
15+
* string convert(string s, int numRows);
16+
*
17+
* 示例 1:
18+
*
19+
* 输入:s = "PAYPALISHIRING", numRows = 3
20+
* 输出:"PAHNAPLSIIGYIR"
21+
* 示例 2:
22+
*
23+
* 输入:s = "PAYPALISHIRING", numRows = 4
24+
* 输出:"PINALSIGYAHRPI"
25+
* 解释:
26+
* P I N
27+
* A L S I G
28+
* Y A H R
29+
* P I
30+
*
31+
* 示例 3:
32+
*
33+
* 输入:s = "A", numRows = 1
34+
* 输出:"A"
35+
*
36+
*
37+
* 提示:
38+
*
39+
* 1 <= s.length <= 1000
40+
* s 由英文字母(小写和大写)、',' 和 '.' 组成
41+
* 1 <= numRows <= 1000
42+
*
43+
*/
44+
pub struct Solution {}
45+
46+
// problem: https://leetcode.cn/problems/zigzag-conversion/
47+
// discuss: https://leetcode.cn/problems/zigzag-conversion/discuss/?currentPage=1&orderBy=most_votes&query=
48+
49+
// submission codes start here
50+
51+
52+
impl Solution {
53+
pub fn convert(s: String, num_rows: i32) -> String {
54+
if num_rows < 2 {
55+
return s.into();
56+
}
57+
let bytes = s.as_bytes();
58+
let mut row: Vec<Vec<u8>> = vec![Vec::with_capacity(s.len()/(num_rows as usize - 1)); num_rows as usize];
59+
60+
let nums_grp = (num_rows - 1) * 2;
61+
for i in (0..s.len()) {
62+
let rem = (i as i32) % nums_grp;
63+
let row_no = if rem > num_rows - 1 {
64+
(num_rows - 1) * 2 - rem
65+
} else {
66+
rem
67+
};
68+
row[row_no as usize].push(bytes[i]);
69+
}
70+
let mut res = Vec::new();
71+
for i in (0..num_rows as usize) {
72+
res.extend(row[i].iter());
73+
}
74+
std::str::from_utf8(&res).unwrap().to_owned()
75+
}
76+
}
77+
78+
// submission codes end
79+
80+
#[cfg(test)]
81+
mod tests {
82+
use super::*;
83+
84+
#[test]
85+
fn test_6() {
86+
assert_eq!(
87+
Solution::convert("PAYPALISHIRING".to_string(), 3),
88+
"PAHNAPLSIIGYIR"
89+
);
90+
assert_eq!(
91+
Solution::convert("PAYPALISHIRING".to_string(), 4),
92+
"PINALSIGYAHRPI"
93+
);
94+
assert_eq!(
95+
Solution::convert("ABC".to_string(), 1),
96+
"ABC"
97+
);
98+
assert_eq!(
99+
Solution::convert("ACB".to_string(), 1),
100+
"ACB"
101+
);
102+
}
103+
}

0 commit comments

Comments
 (0)