Skip to content

Commit

Permalink
Add problem 1961: Check If String Is a Prefix of Array
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 16, 2023
1 parent 66b8398 commit d5856ec
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1479,6 +1479,7 @@ pub mod problem_1941_check_if_all_characters_have_equal_number_of_occurrences;
pub mod problem_1945_sum_of_digits_of_string_after_convert;
pub mod problem_1952_three_divisors;
pub mod problem_1957_delete_characters_to_make_fancy_string;
pub mod problem_1961_check_if_string_is_a_prefix_of_array;

#[cfg(test)]
mod test_utilities;
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn is_prefix_string(s: String, words: Vec<String>) -> bool {
let mut s = s.as_str();

for word in words {
if let Some(next_s) = s.strip_prefix(word.as_str()) {
s = next_s;
} else {
return s.is_empty();
}
}

s.is_empty()
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn is_prefix_string(s: String, words: Vec<String>) -> bool {
Self::is_prefix_string(s, words)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
26 changes: 26 additions & 0 deletions src/problem_1961_check_if_string_is_a_prefix_of_array/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
pub mod dynamic_programming;

pub trait Solution {
fn is_prefix_string(s: String, words: Vec<String>) -> bool;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [
(("iloveleetcode", &["i", "love", "leetcode", "apples"] as &[_]), true),
(("iloveleetcode", &["apples", "i", "love", "leetcode"]), false),
(("z", &["z"]), true),
(("ccccccccc", &["c", "cc"]), false),
];

for ((s, words), expected) in test_cases {
assert_eq!(
S::is_prefix_string(s.to_string(), words.iter().copied().map(str::to_string).collect()),
expected,
);
}
}
}

0 comments on commit d5856ec

Please sign in to comment.