mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
rs: add «165. Compare Version Numbers»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
2808f7d5d8
commit
8222f5e1db
1 changed files with 30 additions and 0 deletions
30
rs/compare-version-numbers.rs
Normal file
30
rs/compare-version-numbers.rs
Normal 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
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue