1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/rs/compare-version-numbers.rs
Matej Focko 8222f5e1db
rs: add «165. Compare Version Numbers»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-05-03 23:40:20 +02:00

30 lines
792 B
Rust

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
}
}