From 2decde61b795a54b6480b05bc1178d989cb7cd41 Mon Sep 17 00:00:00 2001 From: Spxg Date: Sat, 27 Apr 2024 12:18:45 +0800 Subject: [PATCH] Add problem 0393: UTF-8 Validation --- src/lib.rs | 1 + .../iterative.rs | 38 +++++++++++++++++++ src/problem_0393_utf_8_validation/mod.rs | 29 ++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 src/problem_0393_utf_8_validation/iterative.rs create mode 100644 src/problem_0393_utf_8_validation/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 37846b8..3f2d6ab 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -294,6 +294,7 @@ pub mod problem_0387_first_unique_character_in_a_string; pub mod problem_0389_find_the_difference; pub mod problem_0390_elimination_game; pub mod problem_0392_is_subsequence; +pub mod problem_0393_utf_8_validation; pub mod problem_0394_decode_string; pub mod problem_0396_rotate_function; pub mod problem_0397_integer_replacement; diff --git a/src/problem_0393_utf_8_validation/iterative.rs b/src/problem_0393_utf_8_validation/iterative.rs new file mode 100644 index 0000000..7e10aa7 --- /dev/null +++ b/src/problem_0393_utf_8_validation/iterative.rs @@ -0,0 +1,38 @@ +pub struct Solution; + +impl Solution { + pub fn valid_utf8(data: Vec) -> bool { + let mut idx = 0; + let mut count = 0; + while idx < data.len() && count >= 0 { + let bits = (data[idx] & 0b1111_1000) >> 3; + let ones = [0b10000, 0b01000, 0b00100, 0b00010, 0b00001] + .into_iter() + .map(|mask| bits & mask) + .take_while(|&x| x != 0) + .count() as i32; + match ones { + 0 if count == 0 => (), + 1 => count -= 1, + 2..=4 if count == 0 => count = ones - 1, + _ => return false, + } + idx += 1; + } + count == 0 + } +} + +impl super::Solution for Solution { + fn valid_utf8(data: Vec) -> bool { + Self::valid_utf8(data) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_0393_utf_8_validation/mod.rs b/src/problem_0393_utf_8_validation/mod.rs new file mode 100644 index 0000000..e81c6bc --- /dev/null +++ b/src/problem_0393_utf_8_validation/mod.rs @@ -0,0 +1,29 @@ +pub mod iterative; + +pub trait Solution { + fn valid_utf8(data: Vec) -> bool; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + (&[197, 130, 1] as &[_], true), + (&[235, 140, 4], false), + ( + &[206, 210, 189, 208, 197, 163, 182, 171, 212, 243, 10, 0, 10], + false, + ), + (&[230, 136, 145], true), + (&[240, 162, 138, 147], true), + (&[240, 255], false), + (&[255], false), + ]; + + for (data, expected) in test_cases { + assert_eq!(S::valid_utf8(data.to_vec()), expected); + } + } +}