Created
August 16, 2022 13:03
-
-
Save maczniak/40f6abbe232ea0d16ab5d86ae8a960e6 to your computer and use it in GitHub Desktop.
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
// https://leetcode.com/problems/longest-common-prefix/ | |
impl Solution { | |
pub fn longest_common_prefix(strs: Vec<String>) -> String { | |
let mut ret = String::from(""); | |
let mut idx = 0; | |
let mut other_char; | |
loop { | |
other_char = None; | |
for str in &strs { | |
if let Some(c) = str.chars().nth(idx) { | |
if other_char.is_none() { | |
other_char = Some(c); | |
} else if c != other_char.unwrap() { | |
return ret; | |
} | |
} else { | |
return ret; | |
} | |
} | |
ret.push(other_char.unwrap()); | |
idx += 1; | |
} | |
} | |
} |
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
// https://leetcode.com/problems/palindrome-number/ | |
impl Solution { | |
pub fn is_palindrome(x: i32) -> bool { | |
if x < 0 { | |
return false; | |
} | |
let mut x = x; | |
let mut digits = vec![]; | |
while x > 0 { | |
digits.push(x % 10); | |
x = x / 10; | |
} | |
let mut rev_digits = digits.clone(); | |
rev_digits.reverse(); | |
return digits == rev_digits; | |
} | |
} |
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
// https://leetcode.com/problems/roman-to-integer/ | |
impl Solution { | |
pub fn roman_to_int(s: String) -> i32 { | |
let mut ret = 0; | |
let mut last_char = ' '; | |
for c in s.chars() { | |
match c { | |
'M' => if last_char == 'C' { | |
ret += 900 - 100; | |
} else { | |
ret += 1000; | |
}, | |
'D' => if last_char == 'C' { | |
ret += 400 - 100; | |
} else { | |
ret += 500; | |
}, | |
'C' => if last_char == 'X' { | |
ret += 90 - 10; | |
} else { | |
ret += 100; | |
}, | |
'L' => if last_char == 'X' { | |
ret += 40 - 10; | |
} else { | |
ret += 50; | |
}, | |
'X' => if last_char == 'I' { | |
ret += 9 - 1; | |
} else { | |
ret += 10; | |
}, | |
'V' => if last_char == 'I' { | |
ret += 4 - 1; | |
} else { | |
ret += 5; | |
}, | |
'I' => ret += 1, | |
_ => panic!("unknown roman numeral") | |
} | |
last_char = c; | |
} | |
return ret; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment