Skip to content

Commit 228ec11

Browse files
committed
Add problem 848: Shifting Letters
1 parent f50d7be commit 228ec11

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -692,6 +692,7 @@ pub mod problem_0841_keys_and_rooms;
692692
pub mod problem_0844_backspace_string_compare;
693693
pub mod problem_0845_longest_mountain_in_array;
694694
pub mod problem_0846_hand_of_straights;
695+
pub mod problem_0848_shifting_letters;
695696
pub mod problem_0867_transpose_matrix;
696697
pub mod problem_1143_longest_common_subsequence;
697698
pub mod problem_1192_critical_connections_in_a_network;
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn shifting_letters(s: String, shifts: Vec<i32>) -> String {
7+
let mut s = s.into_bytes();
8+
let mut shift = 0;
9+
10+
for (c, &extra_shift) in s.iter_mut().zip(&shifts).rev() {
11+
shift = ((u32::from(shift) + extra_shift as u32) % 26) as u8;
12+
13+
*c += shift;
14+
15+
if *c > b'z' {
16+
*c -= 26;
17+
}
18+
}
19+
20+
String::from_utf8(s).unwrap()
21+
}
22+
}
23+
24+
// ------------------------------------------------------ snip ------------------------------------------------------ //
25+
26+
impl super::Solution for Solution {
27+
fn shifting_letters(s: String, shifts: Vec<i32>) -> String {
28+
Self::shifting_letters(s, shifts)
29+
}
30+
}
31+
32+
#[cfg(test)]
33+
mod tests {
34+
#[test]
35+
fn test_solution() {
36+
super::super::tests::run::<super::Solution>();
37+
}
38+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn shifting_letters(s: String, shifts: Vec<i32>) -> String;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [
13+
(("abc", &[3, 5, 9] as &[_]), "rpl"),
14+
(("aaa", &[1, 2, 3]), "gfd"),
15+
(("ruu", &[26, 9, 17]), "rul"),
16+
];
17+
18+
for ((s, shifts), expected) in test_cases {
19+
assert_eq!(S::shifting_letters(s.to_string(), shifts.to_vec()), expected);
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)