Home  >  Article  >  Java  >  How to compare version numbers using Go Java algorithm

How to compare version numbers using Go Java algorithm

王林
王林forward
2023-04-21 08:46:06891browse

比较版本号

给你两个版本号 version1 和 version2 ,请你比较它们。

  • 版本号由一个或多个修订号组成,各修订号由一个 '.' 连接。每个修订号由 多位数字 组成,可能包含 前导零 。每个版本号至少包含一个字符。

  • 修订号从左到右编号,下标从 0 开始,最左边的修订号下标为 0 ,下一个修订号下标为 1 ,以此类推。例如,2.5.33 和 0.1 都是有效的版本号。

  • 比较版本号时,请按从左到右的顺序依次比较它们的修订号。比较修订号时,只需比较 忽略任何前导零后的整数值 。也就是说,修订号 1 和修订号 001 相等 。

  • 如果版本号没有指定某个下标处的修订号,则该修订号视为 0 。例如,版本 1.0 小于版本 1.1 ,因为它们下标为 0 的修订号相同,而下标为 1 的修订号分别为 0 和 1 ,0 f33c9584fe7aad6577d289ada68c2aee version2 返回 1,

    如果 version1 538b671c07f629eea808ac46dd90c24e v2时返回 1,当v1 00a3b43760e095ee358f56929588b949 num2,返回 1;

  • 如果 num1 < num2,返回 -1;

  • 3、i++,j++,两个指针都后移一步,进行下一轮的修订号解析比较。

  • 4、如果遍历完两个字符串都没有返回相应结果,说明两个字符串相等,返回0。

  • func compareVersion(version1, version2 string) int {
        n, m := len(version1), len(version2)
        i, j := 0, 0
        for i < n || j < m {
            x := 0
            for ; i < n && version1[i] != &#39;.&#39;; i++ {
                x = x*10 + int(version1[i]-&#39;0&#39;)
            }
            i++ // 跳过点号
            y := 0
            for ; j < m && version2[j] != &#39;.&#39;; j++ {
                y = y*10 + int(version2[j]-&#39;0&#39;)
            }
            j++ // 跳过点号
            if x > y {
                return 1
            }
            if x < y {
                return -1
            }
        }
        return 0
    }

    时间复杂度:O(m+n)

    空间复杂度:O(1)

    The above is the detailed content of How to compare version numbers using Go Java algorithm. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete