30 lines
792 B
Rust
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
|
|
}
|
|
}
|