Skip to content

Commit

Permalink
Add problem 0393: UTF-8 Validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed Apr 27, 2024
1 parent ddf82a0 commit 2decde6
Show file tree
Hide file tree
Showing 3 changed files with 68 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 @@ -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;
Expand Down
38 changes: 38 additions & 0 deletions src/problem_0393_utf_8_validation/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
pub struct Solution;

impl Solution {
pub fn valid_utf8(data: Vec<i32>) -> 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<i32>) -> bool {
Self::valid_utf8(data)
}
}

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

pub trait Solution {
fn valid_utf8(data: Vec<i32>) -> bool;
}

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

pub fn run<S: Solution>() {
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);
}
}
}

0 comments on commit 2decde6

Please sign in to comment.