Skip to content

Commit adb4bde

Browse files
committed
Added Reverse String II
1 parent e513a1f commit adb4bde

File tree

2 files changed

+77
-1
lines changed

2 files changed

+77
-1
lines changed

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -445,7 +445,7 @@ pub mod lonely_pixel_i; // 531 ✓
445445
pub mod complex_number_multiplication; // 537 ✓
446446

447447
pub mod single_element_in_a_sorted_array; // 540 ✓
448-
448+
pub mod reverse_string_ii; // 541 ✓
449449
pub mod zero_one_matrix; // 542
450450
pub mod diameter_of_binary_tree; // 543
451451

src/reverse_string_ii.rs

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/// Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k`
2+
/// characters counting from the start of the string.
3+
///
4+
/// If there are fewer than `k` characters left, reverse all of them. If there are less than `2k`
5+
/// but greater than or equal to `k` characters, then reverse the first `k` characters and leave
6+
/// the other as original.
7+
struct Solution;
8+
9+
impl Solution {
10+
11+
pub fn reverse_str(s: String, k: i32) -> String {
12+
let mut stack = Vec::new();
13+
let mut result = Vec::new();
14+
let mut reversed = false;
15+
16+
let k = k as usize;
17+
let mut index = 0;
18+
19+
for c in s.chars() {
20+
if index % (2 * k) == 0 {
21+
reversed = true;
22+
} else if index % k == 0 {
23+
while !stack.is_empty() {
24+
let letter = stack.pop().unwrap();
25+
result.push(letter);
26+
}
27+
reversed = false;
28+
}
29+
30+
if reversed {
31+
stack.push(c);
32+
} else {
33+
result.push(c);
34+
}
35+
36+
index += 1;
37+
}
38+
while !stack.is_empty() {
39+
let letter = stack.pop().unwrap();
40+
result.push(letter);
41+
}
42+
43+
result.into_iter().collect()
44+
}
45+
46+
}
47+
48+
#[cfg(test)]
49+
mod tests {
50+
use super::Solution;
51+
52+
#[test]
53+
fn example_1() {
54+
let s = str!("abcdefg");
55+
let k = 2;
56+
let result = Solution::reverse_str(s, k);
57+
assert_eq!(result, "bacdfeg");
58+
}
59+
60+
#[test]
61+
fn example_2() {
62+
let s = str!("abcd");
63+
let k = 2;
64+
let result = Solution::reverse_str(s, k);
65+
assert_eq!(result, "bacd");
66+
}
67+
68+
#[test]
69+
fn example_3() {
70+
let s = str!("abc");
71+
let k = 4;
72+
let result = Solution::reverse_str(s, k);
73+
assert_eq!(result, "cba");
74+
}
75+
76+
}

0 commit comments

Comments
 (0)