rs: add «165. Compare Version Numbers»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-05-03 23:40:20 +02:00
parent 2808f7d5d8
commit 8222f5e1db
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,30 @@
use std::cmp;
use std::iter;
impl Solution {
fn segments(version: &str) -> Vec<i32> {
version
.split('.')
.map(|s| s.parse::<i32>().expect("valid version is guaranteed"))
.collect()
}
fn extend(segments: &[i32]) -> impl Iterator<Item = &i32> + '_ {
segments.iter().chain(iter::repeat(&0))
}
pub fn compare_version(version1: String, version2: String) -> i32 {
let (s1, s2) = (Self::segments(&version1), Self::segments(&version2));
let length = cmp::max(s1.len(), s2.len());
for (l, r) in Self::extend(&s1).zip(Self::extend(&s2)).take(length) {
if l < r {
return -1;
} else if l > r {
return 1;
}
}
0
}
}