Skip to content

Commit e11cca2

Browse files
committed
Add problem 2000: Reverse Prefix of Word
1 parent ce39c86 commit e11cca2

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -638,6 +638,7 @@ pub mod problem_1929_concatenation_of_array;
638638
pub mod problem_1935_maximum_number_of_words_you_can_type;
639639
pub mod problem_1961_check_if_string_is_a_prefix_of_array;
640640
pub mod problem_1962_remove_stones_to_minimize_the_total;
641+
pub mod problem_2000_reverse_prefix_of_word;
641642
pub mod problem_2032_two_out_of_three;
642643
pub mod problem_2108_find_first_palindromic_string_in_the_array;
643644
pub mod problem_2138_divide_a_string_into_groups_of_size_k;
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
pub struct Solution;
2+
3+
impl Solution {
4+
pub fn reverse_prefix(word: String, ch: char) -> String {
5+
let mut bytes = word.into_bytes();
6+
if let Some(pos) = bytes.iter().position(|&x| x == ch as u8) {
7+
bytes[0..=pos].reverse();
8+
}
9+
String::from_utf8(bytes).unwrap()
10+
}
11+
}
12+
13+
impl super::Solution for Solution {
14+
fn reverse_prefix(word: String, ch: char) -> String {
15+
Self::reverse_prefix(word, ch)
16+
}
17+
}
18+
19+
#[cfg(test)]
20+
mod tests {
21+
#[test]
22+
fn test_solution() {
23+
super::super::tests::run::<super::Solution>();
24+
}
25+
}
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 reverse_prefix(word: String, ch: char) -> 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+
(("abcdefd", 'd'), "dcbaefd"),
14+
(("xyxzxe", 'z'), "zxyxxe"),
15+
(("abcd", 'z'), "abcd"),
16+
];
17+
18+
for ((word, ch), expected) in test_cases {
19+
assert_eq!(S::reverse_prefix(word.to_string(), ch), expected);
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)