Skip to content

Instantly share code, notes, and snippets.

@codedjinn
Last active July 7, 2020 16:31
Show Gist options
  • Select an option

  • Save codedjinn/5d139be670bc238cd0eb3184fd17e819 to your computer and use it in GitHub Desktop.

Select an option

Save codedjinn/5d139be670bc238cd0eb3184fd17e819 to your computer and use it in GitHub Desktop.
Naive solution to problem
/*
Determine whether there exists a one-to-one character mapping from one string s1 to another s2.
For example, given s1 = abc and s2 = bcd, return true since we can map a to b, b to c, and c to d.
Given s1 = foo and s2 = bar, return false since the o cannot map to two characters.
*/
use super::Problem;
pub struct Problem578 {
}
impl Problem578 {
pub fn new() -> Self {
Problem578 {}
}
pub fn can_map(&self, str1: &str, str2: &str) -> bool {
if str1.len() != str2.len() {
return false
}
let chars1 = str1.as_bytes();
let chars2 = str2.as_bytes();
let len = str1.len();
let mut sum1 = 0u64;
let mut sum2 = 0u64;
for i in 0..len {
let b1 = (chars1[i] as u64) << 1;
let b2 = (chars2[i] as u64) << 1;
match (sum1).checked_add(b1 as u64) {
None => return false,
Some(n) => sum1 = n
}
match (sum2).checked_add(b2 as u64) {
None => return false,
Some(n) => sum2 = n
}
}
println!("sum1: {}, sum2: {}", sum1, sum2);
return sum1 == sum2;
}
}
impl Problem for Problem578 {
fn run(&self) {
let str1 = String::from("abcdefghijklmnopqrstuvwxyz");
let str2 = String::from("zyxwvutsrqpomnlkjihgfedcba");
let result = self.can_map(str1.as_str(), str2.as_str());
println!("Result: {}", result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment