|
| 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