Struct Solution

Source
pub struct Solution;

Implementations§

Source§

impl Solution

Source

pub fn compare_version(version1: String, version2: String) -> i32

使用 Iterator 和 Pattern Matching 很简洁

s.split(".") 拆成一个 Iterator,这种东西是 lazy 的,不需要调用 collect() 收集成 Vec,可以直接用 Iterator 的方式处理。

这里用了 fuse() 为了让 Iterator 可以持续调用 next() 直到两个 Iterator 都返回 None 才退出(说明比较完了)。

然后是 Pattern Matching 的方式,直接把所有情况列出。

  • 相同的情况,继续比较下一个
  • 不同的情况,可以直接返回结果
  • 其中一个为 None 的情况,说明这个字符串已经结束了,相当于后面都是 0,只要另一个还有非零的值就比它大(这里题目假设了输入都是有效的,所以不可能是负数)。
  • 最后全部比较完还没有差异,就是相同了,返回 0

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.