LeetCode/rs/compare-version-numbers.rs

31 lines
792 B
Rust
Raw Permalink Normal View History

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