Created
April 14, 2020 19:40
-
-
Save jamesmcm/518dc6a7fd59635045f1bc0ed67e9bab to your computer and use it in GitHub Desktop.
alien_dictionary.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::mem::MaybeUninit; | |
impl Solution { | |
pub fn is_alien_sorted(words: Vec<String>, order: String) -> bool { | |
let order_arr = Solution::get_order_arr(order); | |
words | |
.as_slice() | |
.windows(2) | |
.map(|x| Solution::check_pair(x[0].as_bytes(), x[1].as_bytes(), &order_arr)) | |
.fold(true, |acc, x| acc && x) | |
} | |
fn get_order_arr(s: String) -> [u8; 26] { | |
let mut order_arr: [MaybeUninit<u8>; 26] = unsafe { MaybeUninit::uninit().assume_init() }; //[0; 26]; | |
for (i, byte) in s.as_bytes().iter().enumerate() { | |
unsafe { | |
*order_arr.get_unchecked_mut((*byte - 97) as usize) = MaybeUninit::new(i as u8); | |
} | |
} | |
unsafe { std::mem::transmute::<_, [u8; 26]>(order_arr) } | |
} | |
fn check_pair(word1: &[u8], word2: &[u8], order: &[u8]) -> bool { | |
for (i, c1) in word1.iter().enumerate() { | |
let c2: u8; | |
if let Some(x) = word2.get(i) { | |
c2 = *x - 97; | |
} else { | |
return false; | |
} | |
if order[(*c1 - 97) as usize] < order[c2 as usize] { | |
return true; | |
} | |
if order[(*c1 - 97) as usize] > order[c2 as usize] { | |
return false; | |
} | |
} | |
true | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment