[LeetCode] 165. Compare Version Numbers
Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots ‘.’. The value of the revision is its integer conversion ignoring leading zeros.
To compare version strings, compare their revision values in left-to-right order. If one of the version strings has fewer revisions, treat the missing revision values as 0.
Return the following:
If version1 < version2, return -1.
If version1 > version2, return 1.
Otherwise, return 0.
Example 1:
Input: version1 = “1.2”, version2 = “1.10”
Output: -1
Explanation:
version1’s second revision is “2” and version2’s second revision is “10”: 2 < 10, so version1 < version2.
Example 2:
Input: version1 = “1.01”, version2 = “1.001”
Output: 0
Explanation:
Ignoring leading zeroes, both “01” and “001” represent the same integer “1”.
Example 3:
Input: version1 = “1.0”, version2 = “1.0.0.0”
Output: 0
Explanation:
version1 has less revisions, which means every missing revision are treated as “0”.
Constraints:
1 <= version1.length, version2.length <= 500
version1 and version2 only contain digits and ‘.’.
version1 and version2 are valid version numbers.
All the given revisions in version1 and version2 can be stored in a 32-bit integer.
比较版本号。
给你两个版本号 version1 和 version2 ,请你比较它们。版本号由一个或多个修订号组成,各修订号由一个 ‘.’ 连接。每个修订号由 多位数字 组成,可能包含 前导零 。每个版本号至少包含一个字符。修订号从左到右编号,下标从 0 开始,最左边的修订号下标为 0 ,下一个修订号下标为 1 ,以此类推。例如,2.5.33 和 0.1 都是有效的版本号。
比较版本号时,请按从左到右的顺序依次比较它们的修订号。比较修订号时,只需比较 忽略任何前导零后的整数值 。也就是说,修订号 1 和修订号 001 相等 。如果版本号没有指定某个下标处的修订号,则该修订号视为 0 。例如,版本 1.0 小于版本 1.1 ,因为它们下标为 0 的修订号相同,而下标为 1 的修订号分别为 0 和 1 ,0 < 1 。
返回规则如下:
如果 version1 > version2 返回 1,
如果 version1 < version2 返回 -1,
除此之外返回 0。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/compare-version-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
题意是给两个以字符串展示的版本号,请比较他们的大小。比较的规则很直白,这里核心逻辑是把字符串按.
分割,逐段转成整数进行比较。
复杂度
时间O(n)
空间O(n)
代码
Java实现
1 |
|